角度4 - 观察变量变量的属性

时间:2017-07-12 14:07:50

标签: javascript angular

我想观看json的嵌套属性。只要此嵌套属性更改,就调用fn()。

export class HeaderComponent  {
  user: any;

  constructor(){
    this.user = {
      options: [
        { name: 'Jenny Hess', img: 'assets/img/avatar/small/jenny.jpg' },
        { name: 'Elliot Fu', img: 'assets/img/avatar/small/elliot.jpg' },
        { name: 'Stevie Feliciano', img: 'assets/img/avatar/small/stevie.jpg' }
      ],
      selected: { name: 'Jenny Hess', img: 'assets/img/avatar/small/jenny.jpg' }
    }
  }

Fn更改值

public changeUser(item) {
    this.user.selected = item;
    /*Some Code here*/
}

  public customLogin(user) {
        /*Some Code here*/
        this.user.selected = user;
        /*Some Code here*/
}

每当this.user.selected的值改变时调用一个函数。 我也在使用rxjx

有什么建议吗?

1 个答案:

答案 0 :(得分:8)

你可以这样做:

export class HeaderComponent implements OnDestroy {
  user: any;
  userSelectSubject: BehaviorSubject<{name: string, img: string}>;
  private userSelectSubscription: Subscription;

  constructor(){
    this.user = {
      options: [
        { name: 'Jenny Hess', img: 'assets/img/avatar/small/jenny.jpg' },
        { name: 'Elliot Fu', img: 'assets/img/avatar/small/elliot.jpg' },
        { name: 'Stevie Feliciano', img: 'assets/img/avatar/small/stevie.jpg' }
      ]
    }

    this.userSelectSubject = new BehaviorSubject<{name: string, img: string}>({ name: 'Jenny Hess', img: 'assets/img/avatar/small/jenny.jpg' });

    this.userSelectSubscription = this.userSelectSubject.subscribe((newSelectedUser) => {
      this.user.selected = newSelectedUser;
    });
  }

  ngOnDestroy() {
    this.userSelectSubscription.unsubscribe();
  }
}

然后你只需要调用this.userSelectSubject.next({...})将新选择的用户作为参数传递。