angular - 为什么主页组件中的配置文件详细信息为空
问题描述
如果详细信息为空,我正在尝试调用配置文件 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();
}
}
解决方案
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();
}
}
推荐阅读
- python - 如何从mysql表中只显示输入的生日名称
- angular - 带有茉莉花弹珠的 Ngrx 测试选择器:预期 $.length = 1 到等于 2
- mapping - 处理映射中名称相同但表不同的字段
- angular - 基于Angular 6中选中的复选框调用两种不同方法的一个按钮
- macos - 我的堆栈程序的第一个变量是什么?
- javascript - JavaScript 中的 @Contains 等价物是什么?
- sql-server - 交叉应用 - 查找最新更改
- reactjs - Redux thunk - 异步操作范围更改
- python-3.x - 如何在不使用字符串的情况下检查回文数?
- google-sheets - Google 表格:启用切片器