angular 4 - watch property of a variable for change

前端 未结 1 478
梦如初夏
梦如初夏 2021-01-03 08:46

I want to watch the nested property of a json. Whenever this nested property changes call a fn().

export class HeaderComponent  {
  user: any;

  constructor         


        
相关标签:
1条回答
  • 2021-01-03 09:14

    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.

    0 讨论(0)
提交回复
热议问题