Angular NgRx效果内的角度路由器导航
角度路由器在NgRx效果中是否有任何限制 我刚开始学习NgRx,我有以下代码:Angular NgRx效果内的角度路由器导航,angular,ngrx,angular-router,ngrx-effects,Angular,Ngrx,Angular Router,Ngrx Effects,角度路由器在NgRx效果中是否有任何限制 我刚开始学习NgRx,我有以下代码: @Effect() public authenticate$ = this.actions$ .ofType(authenticationActions.AUTHENTICATE) .switchMap((action: AuthenticateAction) => this.authenticationService.authenticate(action.payload)
@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
操作,因此路由器线路正在执行,但导航没有发生
@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,在分派“AuthenticateSuccesAction”操作时,对重定向执行另一种效果
就我个人而言,我喜欢将所有服务与效果分开,然后在成功登录后使用catchError()操作符在登录失败时调度另一个操作
希望这能奏效。
PS:我没有验证这个答案,但逻辑是这样的。应该有一种方法允许不为重定向创建单独的效果,比如
此.actions$.pipe(
类型(authenticationActions.AUTHENTICATE),
开关映射(操作=>
this.authenticationService.authenticate(action.payload).pipe(
映射(数据=>new authenticationActions.successAction(数据)),
点击(()=>this.router.navigate(['/']),
catchError(错误=>new authenticationActions.failAction(错误))
)
);
问题是,如果服务调用失败,
tap
将不会被调用,map
和tap
都将被跳过,如果出现故障,则选择catchError
。这应该正常工作,在导航到根目录之前,可以尝试其他URL以确保它不是错误?This.router.navigateeByUrl(“/login”)
;确保您没有使用类似AuthGuard的东西将您重定向回登录屏幕。我已经尝试了不同的URL,还禁用了所有的Guard,并在登录页面中创建了一个测试按钮,以使用相同的语句并进行导航。问题是效果中的语句。这非常奇怪,我有类似的imple这很愚蠢,但是,确保你已经将路由器注入了你的构造函数中。在点击操作符中进行导航(在旧版本的rxjs中,它被称为do
)。发送:false是关键;-)@Stuart Allen thx mate!我想知道为什么effect一直在循环有趣地看到您将一个动作发送到reducer和下一个effect处理程序。我会看看这是否有效,但我希望它能起作用。