Angular 检测角度传感器组件内部的特性更改
我正在学习更多关于Angular的知识,并尝试在更改属性后运行一个方法。 这是我的密码Angular 检测角度传感器组件内部的特性更改,angular,typescript,angular-changedetection,Angular,Typescript,Angular Changedetection,我正在学习更多关于Angular的知识,并尝试在更改属性后运行一个方法。 这是我的密码 isLoading = false; ngOnInit() { this.isLoading = true; this._myService.getContent().subscribe( (response: IContent) => { this.isLoading = false; this.doSomething(
isLoading = false;
ngOnInit() {
this.isLoading = true;
this._myService.getContent().subscribe(
(response: IContent) => {
this.isLoading = false;
this.doSomething();
// console.log(response);
},
err => {
this.isLoading = false;
this.doSomething();
console.log(err);
}
);
}
doSomething() {
console.log('some thing')
}
有了这个,我想在isLoading
设置为false后执行doSomething()。我知道我可以把doSomething()放到超时状态
setTimeout(() => this.doSomething(),10);
这会奏效,但我认为有更好的办法。我已经搜索了解决方案并找到了关于ChangeDetectorRef
的信息,我不确定如何在这个案例中实现它。也可能有一种我不熟悉的不同方法。在您的情况下,doSomething
应该在Observable
完成后调用。您可以使用finalize
管道:
isLoading = false;
ngOnInit() {
this.isLoading = true;
this._myService.getContent().pipe(
finalize(() => {
this.isLoading = false;
this.doSomething();
})
).subscribe({
next: (response: IContent) => console.log(response),
error: (error: any) => console.log(err)
});
}
doSomething() {
console.log('some thing')
}
如果您-始终-希望运行doSomething()
,请将this.isLoading
设置为false。您可以使用getter/setter:
get isLoading(): boolean {
return this._isLoading;
}
set isLoading(loading: boolean) {
this._isLoading = loading;
if (loading) {
this.doSomething();
}
}
private _isLoading: boolean;
或者,您可以在类中使用额外的方法:
setLoading(loading: boolean): void {
this.loading = loading;
if (loading) {
this.doSomething();
}
}
最后两个选项不受欢迎,因为功能不再纯粹,因为它们很可能会带来副作用请尝试在组件中实现onPush
或ChangeDetectionStrategy
这样做将指示Angular仅在向这些组件及其子树传递新引用时,而不是在数据发生简单变化时,才对这些组件及其子树运行更改检测
当您更新变量(或执行某些操作)并希望它反映在html中时,请运行this.ref.markForCheck()
或this.ref.detectChanges()
请查看以下链接以了解更多信息
因此,我必须更多地关注rxjs运算符在这类任务中的作用,谢谢。谢谢你的回答,在其他情况下,这肯定会派上用场,因为我不获取,因此不需要rxjs,我也会尝试这样做。