首页 > 解决方案 > 在路由解析器中使用 NGRX

问题描述

我正在使用 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 的正确方法。

任何建议,谢谢

标签: rxjsangular6ngrx

解决方案


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

NgRx 示例应用程序中还有一个守卫示例

@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));
  }
}

推荐阅读