监视变量的属性以进行更改

监视变量的属性以进行更改

本文介绍了角度4-监视变量的属性以进行更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想观看json的嵌套属性.每当此嵌套属性发生更改时,请调用fn().

I want to watch the nested property of a json. Whenever this nested property changes call a 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 .

Whenever the value of this.user.selected changes call a function.I'm using rxjx as well.

有什么建议吗?

推荐答案

您可以执行以下操作:

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({...}),并将新选择的用户作为参数即可.

Then you just need to call this.userSelectSubject.next({...}) passing the new selected user as parameter.

这篇关于角度4-监视变量的属性以进行更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:02