首页 > 解决方案 > Angular 中的 API 调用和生命周期方法

问题描述

我正试图围绕角度及其生命周期方法。以下是我的问题的应对片段。我正在尝试获取已登录的用户,然后使用 user.id 对我的后端进行 API 调用。我尝试将第二个 API 调用移动到更下游的生命周期挂钩,但我反复收到错误,表明 this.user.id 未定义。当我在 ngafterviewchecked 中控制台记录用户对象时,它通过了。任何有关生命周期钩子的帮助或一般建议将不胜感激。这是在 app.component.ts 文件中运行的。我在 React 中的生命周期方法上相当幸运,但是 Angular 让我陷入了循环。

users:any;
userNouns:any;

ngOnInit(){
  this.http.get('http://localhost:8000/users/1')
    .subscribe((result)=>{this.user=result})
}

ngAfterViewChecked(){
  console.log(this.user);
  this.http.get(`http://localhost:8000/nouns/${this.user.id}`)
    .subscribe((result)=>{this.userNouns=result})
}

标签: angularrestapingoninit

解决方案


中的http请求ngOnInit没有阻塞。当您的第一个 http 响应处于挂起状态时,该组件将继续经历其生命周期阶段。

相反,使用 RxJS 运算符将第二个请求链接到第一个请求。您可以使用其中一个switchMapconcatMap将单个可观察对象链接到另一个。您可以tap用于任何副作用(做事)。

users:any;
userNouns:any;

ngOnInit(){
  this.http.get('http://localhost:8000/users/1').pipe(
    tap(result => this.user = result),
    concatMap(user => this.http.get(`http://localhost:8000/nouns/${this.user.id}`)),
    tap(result => this.userNouns = result)
  ).subscribe(() => {
    const contents = this.userNouns.map(noun => noun.content);
    console.log(contents);
  });
}

推荐阅读