Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

264
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda