Angular2 - subscribe to Service variable changes

后端 未结 4 657
时光说笑
时光说笑 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:15

    To keep authenticated in service and share it between components you can use BehaviorSubject, it's value to check authentication in different places, and it's subscribe() method to react on change...

    class AuthService {
      public authenticated = new BehaviorSubject(null);
      getAuthentication() {
        this._http.get('/authenticate')
          .map(response => response.json())
          .map(json => Boolean(json)) // or whatever check you need...
          .subscribe((value: boolean) => this.authenticated.next(value))
      }
    }
    
    class Component {
      constuctor(private _authService: AuthService) {
        // Only check once even if component is 
        // destroyed and constructed again
        if (this._authService.authenticated.value === null)
          this._authService.getAuthentication();
      }
    
      onSubmit(){
        if (!this._authService.authenticated.value)
          throw new Error("You are authenticated!")
      }
    }
    

    How do I execute a function when this.authenticated has changed value?

      this._authService.authenticated
       .subscribe((value: boolean) => console.log(value))
    
    0 讨论(0)
  • 2021-01-30 15:17

    It depends on who needs to handle the event. If it's the parent component, you can leverage output event bindings:

    @Output authenticationChange: EventEmitter<Boolean> = new EventEmitter();
    checkAuthentication(){
         this._authService.getAuthentication()
         .subscribe(value => 
               if(value != this.authenticated) {
                   this.authenticated = value);
                   this.authenticationChange.emit(value);
          });
     }
    

    And in your parent component:

     <directive (authenticationChange)="doSomething()">
    
    0 讨论(0)
  • 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<boolean> = 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
    0 讨论(0)
  • 2021-01-30 15:39

    I used a {{ showValue() }} in the component template, and in the .ts file I called the service's variable

    showValue() {
       this.authenticated = this._authService.authenticated;
       return "dummy"
    } 
    

    Thanks to Angular2's GUI 2-way binding, it works.

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