【问题标题】:Why is profile detail null in the home component为什么主页组件中的配置文件详细信息为空
【发布时间】:2019-06-10 09:25:26
【问题描述】:

如果详细信息为空,我将尝试调用配置文件 api,以避免每次用户回到家时每次路由更改时都调用 api在页面显示之前。

home 组件中的 console.log 为 null,而 auth 服务中的 console.log 打印正确的配置文件数据。

export class HomeComponent {
    activeRoute.data.subscribe((data: any)=> {
      this.userDetail = data.profileDetails;
      console.log(data);
    });
}

应用路由

path: '', component: HomeComponent, resolve: { profileDetails: ProfileDetailsResolverService }

认证服务

 getUserProfile() {
  if(!this.detail) {
    this.http.get(this.userProfileApi).subscribe((res: any)=>{
      console.log(res);
      this.detail = res.data;
      return this.detail;
      } else {
      return this.detail;
      }
   });
  }

配置文件解析器服务

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
      if(localStorage.getItem('access_token')){
      return this.auth.getUserProfile();
    }
  }

【问题讨论】:

  • 您的解析器中是否定义了localStorage.getItem('access_token')
  • 它只是检查令牌是否存在以及用户登录时令牌是否存在。
  • 是的,但它返回undefined 还是一个值?如果您将 if 注释掉会怎样?
  • 你可以检查这个方法getUserProfile()吗?订阅中有一个 else 部分,没有 if 部分..

标签: angular


【解决方案1】:

getUserProfile 不应订阅。角度路由解析器处理这个问题。 shareReplay(1) 确保它执行一次 http 调用。您没有在组件中获取值的原因是因为 getUserProfile 没有返回任何内容:

授权服务:

userProfile$ = this.http.get(this.userProfileApi).pipe(
  map((res) => res.data),
  shareReplay(1)
);


getUserProfile() {
  return this.userProfile$;
}

并将您的解析器更改为:

resolve() {
  if(localStorage.getItem('access_token')){
    return this.auth.getUserProfile();
  }
}

【讨论】:

  • 谢谢,如果配置文件详细信息已经存在,我将如何检查这里不要调用 api。
  • @zuyi 加上shareReplay(1),它只会调用一次。如果你想再次调用它,你应该再次设置userProfile$ 字段
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-29
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多