Angular2中组件属性更改的可观察性

时间:2016-12-22 01:42:06

标签: javascript angular rxjs angular2-directives

在角度2中通过@Input创建具有输入属性的组件时,如何从对该属性@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更改合并,以获得流畅的更改反应模式。

export class ExampleComponent implement OnChanges{
    @Input() userObject: User;

    constructor():{
        userObject.valueChanges.subscribe(x=>{ this.doStuff() });
    }
}

4 个答案:

答案 0 :(得分:3)

我发现BehaviorSubject类使这种情况最好。您可以使用BehaviorSubject的getValue函数以当前值达到峰值,而不是创建单独的后端字段。然后使用支持BehaviorSubject作为更改的可观察对象进行查看。

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(); }
}

答案 1 :(得分:0)

尝试使用get和set,下面的valueChanges()将在设置时触发。

  private _userObject: User;
  @Input()
  set userObject(userObject: User) {
    this._userObject = userObject;
    this.valueChanges();
  }
  get userObject(): User {
    return this._userObject;
  }

使用Observable:

  private userObjectChange = new Subject<User>();
  userObjectChange$ = this.userObjectChange.asObservable();

  private _userObject: User;
  @Input()
  set userObject(userObject: User) {
    this.userObjectChange.next(userObject);
    this._userObject = userObject;
  }
  get userObject(): User {
    return this._userObject;
  }

订阅:

this.newQuote.subscribe(user => {...})

答案 2 :(得分:0)

您可以使用主题:

export class ExampleComponent {
    @Input() set userObject(userObject: User) {
       this.userObject$.next(userObject);
    }

    private userObject$ = new Subject<User>();

    constructor():{
        this.userObject$.subscribe(x=>{ this.doStuff() });
    }
}

答案 3 :(得分:0)

检查输入更改的最佳方法实际上是使用ngOnChanges生命周期。

ngOnChanges(changes: { [propertyName: string]: SimpleChange }) {
  const changedInputs = Object.keys(changes);
  // Only update the userObject if the inputs changed, to avoid unnecessary DOM operations.
  if (changedInputs.indexOf('userObject') != -1) {
  // do something
  }    
}

参考:https://github.com/angular/material2/blob/master/src/lib/icon/icon.ts#L143