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(

我正在学习更多关于Angular的知识,并尝试在更改属性后运行一个方法。 这是我的密码

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,我也会尝试这样做。