如何在路线解析器Angular中返回内部可观察的结果

时间:2020-07-10 19:40:07

标签: angular typescript angularfire rxjs-observables mergemap

我正在尝试编写一种看似简单的方法来获取我的Angular应用程序的用户配置文件详细信息并加载该数据,然后再使用解析器导航至配置文件页面。 。即使没有错误,解析器也不会完成这是我的解析器类代码:

export class ProfileResolverService implements Resolve<Observable<any>> {

  constructor(private fs: FirestoreService, private auth:AuthService) { }

   resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    return this.auth.user.pipe(take(1),
      mergeMap(userdata => {
        return this.fs.getUserProfile(userdata.uid) //get user profile returns  Observable<unknown[]>
      })
    )
    
  }
   
}

并在我的路由模块中:

path: 'profile',
            children: [
                {
                    path: '',
                    resolve: {
                      userdata: ProfileResolverService
                    },
                    loadChildren: () => import('../profile/profile.module').then( m => m.ProfilePageModule)
                }

任何人都可以帮忙。持续了2天

2 个答案:

答案 0 :(得分:0)

可能有两个原因:

  • this.auth.user不发出任何值
  • this.fs.getUserProfile(userdata.uid)未完成

尝试此操作以查看是否有日志:

    return this.auth.user.pipe(
      take(1),
      mergeMap(userdata => {
        console.log('userdata: ', userdata);
        return this.fs.getUserProfile(userdata.uid).pipe(
          tap(profile => console.log('profile: ', profile));
          finalize(() => console.log('getUserProfile complete or error'));
        )
      })
    )

如果代码正确,则至少应具有日志userdata和getUserProfile

答案 1 :(得分:0)

发现那里的问题:

export class ProfileResolverService implements Resolve<Observable<any>> {

  constructor(private fs: FirestoreService, private auth:AuthService) { }

   resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    return this.auth.user.pipe(take(1),
      mergeMap(userdata => {
        return this.fs.getUserProfile(userdata.uid).pipe(take(1),map(user => user)); //had to map the output of the observable and then fetch it in my rout resolver
      })
    )
    
  }
   
}```

So my resolver now looks like this:

路径:“个人资料”, 儿童:[ { 路径:“, 解决:{ 用户:ProfileResolverService \获取用户而不是用户数据 }, loadChildren:()=> import('../ profile / profile.module')。then(m => m.ProfilePageModule) }