如何 return 路由解析器中内部可观察结果 Angular

How to return result of inner observable in route resolver Angular

我正在尝试编写一个看似简单的方法来为我的 Angular 应用程序获取用户个人资料详细信息,并在使用解析器导航到个人资料页面之前加载该数据。 .即使没有错误,解析器也没有完成这是我的解析器代码 class:

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 天了

可能有两个原因:

  • 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'));
        )
      })
    )

如果你的代码没问题,你至少应该有日志用户数据和getUserProfile

在那里发现问题:

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:

路径:'profile', children:[ { 小路: '', 解决: { 用户:ProfileResolverService \获取用户而不是用户数据 }, loadChildren: () => import('../profile/profile.module').then( m => m.ProfilePageModule) }


我遇到了完全相同的问题。 看来您必须订阅可观察对象才能让解析器解析。

所以在你的情况下,它应该是这样的:

    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[]>
      })
    ).subscribe()
    
  }