【问题标题】:Using NGRX in a Route Resolver在路由解析器中使用 NGRX
【发布时间】:2019-02-05 14:00:34
【问题描述】:

我正在使用 Angular 6。 我也在使用 NGRX 商店。 我正在使用路由保护来确保用户登录到应用程序。 然后我使用解析器获取初始用户配置文件,然后将其放置在 NGRX 存储中。

我是 NGRX 的新手,我不确定这是否是编写解析器的正确方法。

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
     return this.loginService.getLoginData()
        .pipe(
            map((result:UserData) => { 
                this.store.dispatch(new userActions.SetLoginData(result)); 
                this.loginService.getDropdownData(
                    result.userId, 
                    result.countryCode,
                ).subscribe( data => { 
                    this.store.dispatch(new userActions.SetDropdownData(data));
                })
            })
        )
}  

我也不确定这是否是执行 RXJS 的正确方法。

任何建议, 谢谢

【问题讨论】:

    标签: rxjs angular6 ngrx


    【解决方案1】:

    我将向您指出Preloading ngrx/store with Route Guards,Todd Motto 的一篇文章很好地解释了这一点。

    NgRx example app中也有守卫的例子

    @Injectable()
    export class CoursesGuard implements CanActivate {
      constructor(private store: Store<CoursesState>) {}
    
      getFromStoreOrAPI(): Observable<any> {
        return this.store
          .select(getCoursesState)
          .do((data: any) => {
            if (!data.courses.length) {
              this.store.dispatch(new Courses.CoursesGet());
            }
          })
          .filter((data: any) => data.courses.length)
          .take(1);
      }
    
      canActivate(): Observable<boolean> {
        return this.getFromStoreOrAPI()
          .switchMap(() => of(true))
          .catch(() => of(false));
      }
    }
    

    【讨论】:

      【解决方案2】:

      首先,我认为将身份验证检查和数据解析分成单独的类是有意义的。对于身份验证,使用CanActivate 保护更有意义。见:https://angular.io/api/router/CanActivate

      这样一来,您的解析器就可以专注于仅获取实际需要的数据。在这里您需要注意,如果您在解析器中返回一个可观察对象,则该可观察对象需要完成才能使解析器完成。问题是,如果您从商店中选择某些东西,则生成的 observable 永远不会完成,因此您的解析器将永远无法完成解析您的数据。您可以使用first()take(1) 运算符来解决这个问题。 timdeschryvers 的答案有一个很好的例子来说明如何做到这一点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-28
        • 1970-01-01
        • 2016-11-16
        • 2017-06-21
        • 1970-01-01
        • 2015-08-05
        • 1970-01-01
        相关资源
        最近更新 更多