Angular2 中组件属性变化的 Observable [英] Observable of Component Attribute Changes in Angular2

查看:22
本文介绍了Angular2 中组件属性变化的 Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 angular 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 中组件属性变化的 Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆