ngOnChanges 多次调用

Abh*_*oni 4 ionic-framework angular ionic4 angular7

我使用 ngFor 生成了多个离子幻灯片,并在那里插入了一个组件。它多次调用 ngOnChanges。我希望它只调用一次,以便我可以调用我的 api。

我尝试过使用多个角度生命周期挂钩。

这就是我创建幻灯片的方式,菜单有 19 个元素

<ion-slides #slides [options]="slideOpts" (ionSlideDidChange)="slideChanged($event)">
<ion-slide *ngFor="let i of menu; let j = index">
  <h1>{{ i.name }}</h1>
  <app-homenews [categoryId]="currentCategoryId" ></app-homenews>
</ion-slide>
</ion-slides>
Run Code Online (Sandbox Code Playgroud)

这就是我们进行变更检测的方式

@Input() categoryId: number;

ngOnChanges(changes: SimpleChanges) {
   let chg = changes['categoryId'];
   console.log(chg.currentValue);
} 
Run Code Online (Sandbox Code Playgroud)

我希望它只被调用一次,现在它已经调用了 19 次。

我可以在这里使用 rxjs 吗?

小智 5

ngOnChanges当来自模板绑定的输入变量的值发生变化时运行。因此多次触发它是正常行为。如果您只想执行某些代码一次,您可以像这样使用它

@Input() isFirstRun;
ngOnChanges(changes: SimpleChanges) {
  if(this.isFirstRun){
     let chg = changes['categoryId'];
     console.log(chg.currentValue);
  }
}

<ion-slide *ngFor="let i of menu; let j = index">
  <h1>{{ i.name }}</h1>
  <app-homenews [isFirstRun]="j===0?true:false" [categoryId]="currentCategoryId" ></app-homenews>
</ion-slide>
Run Code Online (Sandbox Code Playgroud)