NgRx效果中的角度路由器导航

RBa*_*iak 7 ngrx ngrx-effects angular angular-router

Angular路由器在NgRx效果中是否有任何限制?

我刚开始学习NgRx,我有以下代码:

@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); })
        );
Run Code Online (Sandbox Code Playgroud)

控制台记录数据变量并AuthenticateSuccessAction触发操作,因此正在执行路由器线,但导航不会发生.

m.a*_*ari 18

@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(['/']))
   );
Run Code Online (Sandbox Code Playgroud)

使用exhaustMap并在分派"AuthenticateSuccessAction"操作时,为重定向执行另一个效果.

就个人而言,我喜欢将所有服务与效果分开,然后您可以在成功登录后使用catchError()运算符,以便在登录失败时调度另一个操作.

希望这有效.PS:我没有验证这个答案,但逻辑是这样的.

  • 该调度:假是关键;-) (4认同)
  • @Stuart Allen 谢谢,伙计!我想知道为什么效果一直循环 (2认同)

dhi*_*ilt 11

应该有一种方法允许不为重定向创建单独的效果,例如

this.actions$.pipe(
  ofType(authenticationActions.AUTHENTICATE),
  switchMap(action =>
    this.authenticationService.authenticate(action.payload).pipe(
      map(data => new authenticationActions.successAction(data)),
      tap(() => this.router.navigate(['/'])),
      catchError(error => new authenticationActions.failAction(error))
    )
);
Run Code Online (Sandbox Code Playgroud)

问题是,tap如果服务调用失败将不会被调用,都maptap将有利于被跳过catchError,如果失败案例。


小智 5

根据 m.akbari 的响应,如果他们使用不同的操作,“dispatch : false”将转到最后一个

关键是“ dispatch: false ”,如果没有指示,则会生成无限循环

 loginNavigate$ = createEffect(
    () => this.actions$.pipe(
        ofType(usuariosActions.loginUsuarioSuccess),
        tap(() => {
            console.log('iniciando la navegacion');

            this.router.navigate(['/']);
        })
    ), { dispatch: false }
);
Run Code Online (Sandbox Code Playgroud)