这是我经常遇到的一个问题,当我的应用由声明性组件组成时(因此它们的模板可以通过其属性的值完全可预测),但有时某个主体会以一种被动的方式推动新的价值。
比方说,我有这样的东西:一个基于数组元素的组件列表。
<hello *ngFor="let h of helloComponents"></hello>
hello组件已从服务预订到BehaviorSubject。
[在某个时候(例如,单击按钮时)behaviorSubject会发出新值,但数组也会更新。
事件的顺序如下:
问题是旧组件在被销毁之前就已接收到该值,因此它们可能会运行我不希望它们执行的代码,因为它们在第3点被销毁了。
如果我先更新数组,然后从主题推送新值,则情况不会改变。
我找到2个修复程序:
A。使用setTimeout可以确保当旧组件已被Angular Change Detection销毁时,主体会发出新值。但是我不知道这个解决方案有多强大...
this.myarray= [4, 5];
setTimeout(() => subject.next(new value));
B。使用observeOn(asyncScheduler)
this.stateService.state$.pipe(
observeOn(asyncScheduler)
).subscribe(
state => console.log(`helloComponent ${this.id}, state: ${state}`)
)
但是我真的是一个关于Rxjs Scheduler的新手,我不知道这是一个好方法还是有更好的选择。
Here is the stackblitz... open the console
有什么想法吗?
helloComponents
数组,它似乎可以正常工作:import { Component, ChangeDetectorRef } from '@angular/core';
import { StateService } from './state.service';
@Component({
selector: 'my-app',
template: `<hello *ngFor="let h of helloComponents, trackBy: trackById" [id]="h"></hello> <button (click)="action()">action</button>`
})
export class AppComponent {
name = 'Angular';
helloComponents = [1, 2, 3];
constructor(private stateService: StateService, private ref: ChangeDetectorRef) {}
action() {
this.helloComponents = [4, 5];
this.ref.detectChanges();
this.stateService.action();
}
trackById = id => id;
}
stackblitz:https://stackblitz.com/edit/angular-e9zfoq?file=src/app/app.component.ts