在多个地方使用订阅行为对象进行加载的组件时,获得
ExpressionChangedAfterItHasBeenCheckedError
。当在一个组件中加载组件并尝试在另一组件中加载 load
或 destroy
时,会发生错误。
@Component({
template: 'common.component.html',
selector: 'app-common'
})
export CommonComponent implements OnInit{
constructor(service: MyService){}
ngOnInit(){
}
}
**common.component.html**
<div>
<div *ngIf="service.isLoading$ | async">Loading...</div>
</div>
**component 1**
<div>
<app-common></app-common>
</div>
component 2
<div>
<app-common></app-common>
</div>
@Injectable()
export class MyService {
public isLoading = new BehaviorSubject<any>(false);
public isLoading$ = this.isLoading.asObservable();
}```
public isLoading$ = this.isLoading.asObservable().pipe(delay(0))
更多相关信息
使用 ChangeDetectionStrategy.OnPush
import { ChangeDetectionStrategy } from '@angular/core';
@Component({template: 'common.component.html',
selector: 'app-common',
changeDetection: ChangeDetectionStrategy.OnPush
})
尝试移动
<div *ngIf="service.isLoading$ | async">Loading...</div>
到另一个子组件。这对我有用。