NgRx 效果中的角度路由器导航 [英] Angular router navigation inside NgRx effect
问题描述
Angular 路由器在 NgRx 效果中使用有任何限制吗?
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 效果中的角度路由器导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!