简体   繁体   中英

How to get the new value of a variable in another function after it was changed inside a different function, in Angular ...service.ts

I have a service file auth.service.ts

 export class AuthService { private _isLoggedIn = new BehaviorSubject<boolean>(false); isLoggedIn = this._isLoggedIn.asObservable() constructor(private http: HttpClient) {} //if admin //setter method updateAuthenticated(newValue: boolean){ this._isLoggedIn.next(newValue); } //for guarding routes //getter method isAuthenticated(){ return this.isLoggedIn.subscribe(isLoggedIn =>{ console.log(isLoggedIn); }); }

On calling the updateAuthenticated() method inside the login.component.ts

 this.authService.updateAuthenticated(true); this.route.navigate(['/admin']);

Changes made to the variable inside the updateAuthenticated() method are not reflected if I check the variable value in isAuthenticated() method which still remains "false" as initialized. However, Checking the value inside the setter method returns the correct value. I tried using BehaviourSubject and can't get it right. Is there a way to get the new value inside the isAuthenticated() method (getter method) or what am I doing wrong with the BehaviourSubject?

The function isAuthenticated() inside the service will not emit the value, because it will return you the whole observable instance. You need to subscribe to the observable isLoggedIn directly inside the component where you need to listen for the BehaviorSubject event.

So instead of putting isAuthenticated() is the service.ts file, go the component that needs the emitted value, and do following:

export class SomeComponent implements OnInit() {
  latestValue: boolean;

  constructor(private authService: AuthService) {}

  ngOnInit() {
    this.authService.isLoggedIn.subscribe(isLoggedIn =>{
      this.latestValue = isLoggedIn;
      // now use this.latestValue within the component
    });

  }
}

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