在Angular2中可观察到的组件属性变化 [英] Observable of Component Attribute Changes in Angular2
问题描述
当在角2中创建一个具有通过@Input输入属性的组件时,如何从对该属性@Input所做的更改中得到一个可观察到的信息(不要与用户表单输入相混淆).
When creating a component in angular 2 that has inputs attributes via @Input, how can I get an observable from the changes made to that attribute @Input (not to be confused with user form input).
export class ExampleComponent implement OnChanges{
@Input() userObject: User;
ngOnChanges(changes: any): void{
// Validate that its the 'userObject' property first
this.doStuff()
}
}
在实践中,我想将userObject的Observable更改与其他事物的Observable更改合并,以形成流畅的更改反应模式.
In practice, I would like to merge the Observable changes of the userObject with the Observable changes of other things to have a fluent change reaction pattern.
export class ExampleComponent implement OnChanges{
@Input() userObject: User;
constructor():{
userObject.valueChanges.subscribe(x=>{ this.doStuff() });
}
}
推荐答案
我发现BehaviorSubject类可以最好地实现此方案.代替创建单独的后端字段,您可以使用BehaviorSubject的getValue
函数使当前值达到峰值.然后使用后盾BehaviorSubject将其视为可观察到的更改.
I found out the that BehaviorSubject class enables this scenario the best. Instead of creating a separate backend field, you can use the BehaviorSubject's getValue
function to peak at the current value. Then use the backing BehaviorSubject to view as an observable for changes.
export class ExampleComponent{
private _userObject: BehaviorSubject<User> = new BehaviorSubject<User>(null);
@Input()
set userObject(value: User): { this._userObject.next(value); }
get userObject(): User { return this._userObject.getValue(); }
}
这篇关于在Angular2中可观察到的组件属性变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!