问题描述
在NgRx效果中使用Angular路由器有什么限制吗?
Does the Angular router have any restrictions to be used inside an NgRx effect?
我刚刚开始学习NgRx,我有以下代码:
I just started learning NgRx and I have the following code:
@Effect() public authenticate$ = this.actions$
.ofType(authenticationActions.AUTHENTICATE)
.switchMap((action: AuthenticateAction) => this.authenticationService.authenticate(action.payload)
.map((data: TokenData) => {
const user: User = {
token: data.token,
username: 'dummy',
};
console.log(data);
this.router.navigateByUrl('/');
return new authenticationActions.AuthenticateSuccessAction(user);
})
.catch(error => { console.log(error); return Observable.throw(error); })
);
控制台会记录数据变量,并且会触发 AuthenticateSuccessAction
操作,因此正在执行路由器线路,但不会进行导航.
The console logs the data variable and the AuthenticateSuccessAction
action is being triggered, so the router line is being executed but the navigation doesn't happen.
推荐答案
@Effect() public authenticate$ = this.actions$.pipe(
ofType(authenticationActions.AUTHENTICATE),
map(action => action.payload),
exhaustMap((auth: any) =>
this.authenticationService.authenticate(auth)
.map((data: TokenData) => {
return user: User = {
token: data.token,
username: 'dummy',
};
}).catch(error => { console.log(error); return Observable.throw(error);
}).pipe(
map(user =>new authenticationActions.AuthenticateSuccessAction(user))
)
);)
@Effect({ dispatch: false })
loginSuccess$ = this.actions$.pipe(
ofType(authenticationActions.AuthenticateSuccessAction),
tap(() => this.router.navigate(['/']))
);
使用exhaustMap,并在分派"AuthenticateSuccessAction"操作时,对重定向产生另一种效果.
Use exhaustMap and when you dispatching 'AuthenticateSuccessAction' action, do another effect for redirecting.
我个人希望将所有服务与效果分开,然后您可以在成功登录后使用catchError()运算符,以在失败登录的情况下调度另一个操作.
Personally, I like to separate all the services from effects, then you can use catchError() operator after success login for dispatching another action in case of failure login.
希望这行得通.PS:我没有验证这个答案,但是逻辑是这样的.
hope this works.PS: I did not verify this answer but logic is like this.
这篇关于NgRx效果内的角路由器导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!