我正在尝试在 Observable
/subscribe
完成后做一些事情。我正在更改 subscribe( onNext )
方法中的 Input
属性,但 ngOnChanges
从未触发。
我应该做些什么不同的事情?
import { Component, EventEmitter,
OnInit, AfterViewInit, OnChanges, SimpleChanges,
Input, Output
} from '@angular/core';
@Component({
templateUrl: 'myTemplate.html'
, providers: [ NamesService ]
})
export class MyPage {
@Input() names: any[];
constructor( public namesSvc: NamesService) {}
ngOnInit() {
this.getNames$()
}
getNames$() : void {
this.nameService.get().subscribe(
(result)=>{
this.names = result;
console.log(`getNames$, names=${this.names}`);
// I could doSomething() here, but it doesn't seem like the correct place
// doSomething()
}
, error => this.errorMessage = <any>error
)
}
ngOnChanges(changes: SimpleChanges) : void {
// changes.prop contains the old and the new value...
console.warn(`>>> ngOnChanges triggered`)
if (changes["names"]) {
console.warn(`>>> ngOnChanges, names=${changes["names"]}`)
this.doSomething()
}
}
doSomething(){
console.log("doing something");
}
}
最佳答案
这是“按设计”
ngOnChanges()
仅在更改检测更新绑定(bind)到 @Input()
时调用。如果输入从某处强制更改,则不会调用它。
只需将 names
设置为每次属性更新时要执行的代码的 getter/setter。
关于angular - 当 Observable/订阅更改属性时 ngOnChanges 不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39913255/