当属性由Observable/subscrption更改时,ngOnChanges不触发 [英] ngOnChanges not firing when attribute changed by Observable/subscrption
本文介绍了当属性由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()
.如果从某处命令性地更改了输入,则不会调用它.
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
用作每次属性更新时要执行的代码的获取器/设置器即可.
Just make names
a getter/setter for code to be executed every time when the property is updated.
这篇关于当属性由Observable/subscrption更改时,ngOnChanges不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文