Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

271
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda