简体   繁体   中英

angular 4 - watch property of a variable for change

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 changes values

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

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

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

Any suggestion??

You could do something like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM