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

266
Views
Cómo obtener el nuevo valor de una variable en otra función después de que se cambió dentro de una función diferente, en Angular ...service.ts

Tengo un archivo de servicio 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); }); }

Al llamar al método updateAuthenticated() dentro de login.component.ts

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

Los cambios realizados en la variable dentro del método updateAuthenticated() no se reflejan si verifico el valor de la variable en el método isAuthenticated() que sigue siendo "falso" como se inicializó. Sin embargo, Verificar el valor dentro del método setter devuelve el valor correcto. Intenté usar BehaviourSubject y no puedo hacerlo bien. ¿Hay alguna manera de obtener el nuevo valor dentro del método isAuthenticated () (método de obtención) o qué estoy haciendo mal con BehaviourSubject?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

La función isAuthenticated() dentro del servicio no emitirá el valor, porque le devolverá toda la instancia observable. Debe suscribirse al isLoggedIn observable directamente dentro del componente donde necesita escuchar el evento BehaviorSubject .

Entonces, en lugar de poner isAuthenticated() es el archivo service.ts, vaya al componente que necesita el valor emitido y haga lo siguiente:

 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!