首页 > 解决方案 > ngOnInit() 被调用两次并获得两个 API 响应

问题描述

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>

ngOnInit()据我所知,该 API 被调用了两次。为什么会这样,我该如何解决这个问题?

标签: angularlifecyclengoninitangular-lifecycle-hooks

解决方案


推荐阅读