本文介绍了当 Observable/subscrption 更改属性时,ngOnChanges 不会触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 Observable
/subscribe
完成后做一些事情.我正在更改 subscribe( onNext )
方法中的 Input
属性,但 ngOnChanges
永远不会触发.
I'm trying to do something after an Observable
/subscribe
completes. I'm changing an Input
property in the subscribe( onNext )
method, but ngOnChanges
never fires.
我应该怎么做?
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()
仅在更改检测更新与 @Input()
的绑定时调用.如果从某处强制更改输入,则不会调用它.
ngOnChanges()
is only called when change detection updates a binding to an @Input()
. If the input is changed imperatively from somewhere then it isn't called.
只需让 names
成为每次更新属性时执行的代码的 getter/setter.
Just make names
a getter/setter for code to be executed every time when the property is updated.
这篇关于当 Observable/subscrption 更改属性时,ngOnChanges 不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!