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()
被调用了两次。这是为什么?我该如何解决这个问题?
使用下面的函数跳过并获取发出的事件。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.
});
}