在Angular 6中执行父路由页面中的promise回调之前,将执行子路由页面中的代码

我有一个页面组件,其路由文件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,我正在使用公共获取程序公开此值,以便可以从其他组件访问它。 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'为空。我如何才能在home.component.ts中的代码之前执行pages.component.ts文件中的回调代码?请帮我解决这个问题

samdd 回答:在Angular 6中执行父路由页面中的promise回调之前,将执行子路由页面中的代码

像这样简单地进行更改

在common.service.ts文件中

public get currentUserValue(): any {
    return  this.currentUserSubject.asObservable();
 } 

并在您的home.component.ts文件中

 ngOnInit(){
     this.commonService.currentUserValue.subscribe(user => console.log(user));
  }
本文链接:https://www.f2er.com/2694122.html

大家都在问