【问题标题】:Code in the child route page getting executed before the promise callback in parent route page is executed in Angular 6在 Angular 6 中执行父路由页面中的承诺回调之前执行子路由页面中的代码
【发布时间】: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


    【解决方案1】:

    像这样进行更改很简单

    在您的 common.service.ts 文件中

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

    在你的 home.component.ts 文件中

     ngOnInit(){
         this.commonService.currentUserValue.subscribe(user => console.log(user));
      }
    

    【讨论】:

    • 嗨。我尝试了这种方法,但是 home.component.ts 中 subscribe 中的代码仍然在 pages.component.ts 中的“then”回调中的代码之前执行,并且 subscribe 中的用户值为 null
    猜你喜欢
    • 2019-07-24
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    相关资源
    最近更新 更多