Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

261
Views
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?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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
    });

  }
}
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!