【发布时间】:2020-05-14 14:06:06
【问题描述】:
我有一个页面组件,其路由文件 pages.routing.ts 具有以下路由
const routes: Routes = [
{
path: 'pages',
component: PagesComponent,
children: [
{ path: 'home', loadChildren: './home/home.module#HomeModule'}
]
}
];
pages.component.ts文件里面的代码是
ngOnInit() {
this.commonService.canAccess()
.then(response => {
if(response['data']) {
sessionStorage.setItem('currentUser', JSON.stringify(response['data']));
this.commonService.updateCurrentUserValue(response['data']);
}
},
() => {
// handle error here
});
}
在公共服务中,我有一个“currentUserSubject”,它是一个 BehaviorSubject,我使用公共 getter 公开此值,以便我可以从其他组件访问它。 common.service .ts 文件中的代码是
constructor(private http: HttpClient) {
this.currentUserSubject = new BehaviorSubject<string>(sessionStorage.getItem('currentUser'));
}
public get currentUserValue(): any {
return JSON.parse(this.currentUserSubject.value);
}
public updateCurrentUserValue(currentUser: any) {
this.currentUserSubject.next(JSON.stringify(currentUser));
}
async canAccess() {
return await this.http.request('GET', this.apiUrl, httpOptions)
.pipe(
map(response => {
return response;
}))
.toPromise();
}
现在我正在尝试在 home.component.ts 文件中使用 currentUserValue,如下所示。
ngOnInit() {
const currentUser = this.commonService.currentUserValue;
}
问题是在 pages.component.ts 文件中的 'then' 回调中的代码执行之前, home.component.ts 文件中的 ngOnInit 中的代码被执行并且 home 组件中的 'currentUser' 为空。如何使 pages.component.ts 文件中的回调代码在 home.component.ts 中的代码之前执行?请帮我解决这个问题
【问题讨论】:
标签: angular typescript promise rxjs es6-promise