ngOnInit() 被调用两次并获得两个 API 响应

问题描述 投票:0回答:1

app.component.ts

export class AppComponent implements OnInit{
  title = "quogen";
  response : Response[];

  constructor (private dataService : DataService) {

  }
  ngOnInit () {
      console.log("calling init");
      return this.dataService.getQuote().subscribe(data => this.response = data);
  }
}

app.component.html

<div *ngIf="response">
  <p>{{ response['content'] }}</p>
  <p>{{ response['author'] }}</p>
</div>
<router-outlet></router-outlet>

据我所知,该 API 从

ngOnInit()
被调用了两次。这是为什么?我该如何解决这个问题?

angular lifecycle ngoninit angular-lifecycle-hooks
1个回答
0
投票

使用下面的函数跳过并获取发出的事件。skip(1)运算符跳过第一次发射,然后使用take(1)确保订阅方法只处理第二次发射。

 ngOnInit(): void {
this.route.queryParams
  .pipe(skip(1), take(1)) // Skip the first emission and take the second one
  .subscribe(params => {
    this.code = params['code'];
    // You can now use this.code in your component.
  });

}

© www.soinside.com 2019 - 2024. All rights reserved.