Angular2 - subscribe to Service variable changes

后端 未结 4 664
时光说笑
时光说笑 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))
    

提交回复
热议问题