ChangeDetectionStrategy.OnPush 接收到从服务中解构的对象时似乎不起作用?
ChangeDetectionStrategy.OnPush does not seem to be working when receiving an object destructured from a service?
我正在使用 OnPush 策略,我有一个更新一些数据的服务,当我在组件中收到它时,我必须点击屏幕才能看到屏幕上的变化。
Parent.ts
// Click start the logic
click() {
this.showChild = true;
setTimeout(()=> this.update, 0); // Hack to show the loading in the component until it receives a value from the service
}
update() {
this.explorer.getData().subscribe(data => {
this.info = {...data};
// this.cdr.detectChanges();
});
}
Parent html
<app-child *ngIf="showChild" [info]="info" [otherVar]="otherVar"></app-child>
我知道在使用解构时会有引用更改,但我看不到它起作用。有谁知道我做错了什么?
只有在 @Input
上,引用更改才会触发具有 OnPush 更改检测策略的组件的更改检测
我在 Stackblitz. Using OnPush everywhere with the Async Pipe
写了一个小例子
Parent.ts
// Observable Variable declaration
info$: Observable<InfoModel>;
// Click start the logic
click() {
this.showChild = true;
setTimeout(()=> this.update, 0); // Hack to show the loading in the component until it receives a value from the service
}
update() {
// instead of subscribing here, retrieve just the Observable
this.info$ = this.explorer.getData();
}
Parent html
<!--<app-child *ngIf="showChild" [info]="info" [otherVar]="otherVar"></app-child>-->
<app-child *ngIf="showChild" [info]="info$ | async" [otherVar]="otherVar"></app-child>
我正在使用 OnPush 策略,我有一个更新一些数据的服务,当我在组件中收到它时,我必须点击屏幕才能看到屏幕上的变化。
Parent.ts
// Click start the logic
click() {
this.showChild = true;
setTimeout(()=> this.update, 0); // Hack to show the loading in the component until it receives a value from the service
}
update() {
this.explorer.getData().subscribe(data => {
this.info = {...data};
// this.cdr.detectChanges();
});
}
Parent html
<app-child *ngIf="showChild" [info]="info" [otherVar]="otherVar"></app-child>
我知道在使用解构时会有引用更改,但我看不到它起作用。有谁知道我做错了什么?
只有在 @Input
上,引用更改才会触发具有 OnPush 更改检测策略的组件的更改检测我在 Stackblitz. Using OnPush everywhere with the Async Pipe
写了一个小例子Parent.ts
// Observable Variable declaration
info$: Observable<InfoModel>;
// Click start the logic
click() {
this.showChild = true;
setTimeout(()=> this.update, 0); // Hack to show the loading in the component until it receives a value from the service
}
update() {
// instead of subscribing here, retrieve just the Observable
this.info$ = this.explorer.getData();
}
Parent html
<!--<app-child *ngIf="showChild" [info]="info" [otherVar]="otherVar"></app-child>-->
<app-child *ngIf="showChild" [info]="info$ | async" [otherVar]="otherVar"></app-child>