Angular2 - subscribe to Service variable changes

后端 未结 4 665
时光说笑
时光说笑 2021-01-30 15:01

I have an authentication service that makes the authenticated variable equal to true or false.

checkAuthentication(){
  this._authService.getAuthentication()
           


        
4条回答
  •  佛祖请我去吃肉
    2021-01-30 15:23

    I think that you could leverage the get / set syntax of TypeScript to detect when your authenticated property of your service is updated:

      private _authenticated:Boolean = false;
      get authenticated():Boolean {
            return this._authenticated ;
      }
      set authenticated ( authenticated Boolean) {
        // Plugin some processing here
          this._ authenticated = authenticated;
      }
    

    When assigning a value, the "set authenticated" block is called. For example with such code:

    this.authenticated = true;
    

    See this question for more details:

    • get and set in TypeScript

    That said you could also leverage an EventEmitter property in the service. When the authenticated property is updated, the corresponding event could be fired.

    export class AuthService {
      authenticatedChange: Subject = new Subject();
    
      constructor() {}
    
      emit(authenticated) {
        this.authenticatedChange.next(authenticated);
      }
    
      subscribe(component, callback) {
        // set 'this' to component when callback is called
        return this.authenticatedChange.subscribe(data => {
          callback(component, data);
        });
      }
    }
    

    See this link for more details:

    • Delegation: EventEmitter or Observable in Angular2

提交回复
热议问题