首页 > 解决方案 > 为什么主页组件中的配置文件详细信息为空

问题描述

如果详细信息为空,我正在尝试调用配置文件 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();
    }
  }

标签: angular

解决方案


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

推荐阅读