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

151
Views
Make button to wait for mehtod to resolve

I have a couple of buttons that I want to display only if user is logged in. My problem is that simple *ngIf is not working like I want it to. For example I have this button Add Recipe:

<div class="background">
<button type="button" *ngIf="isUserAuthenticated" class="btn btn-primary float-right m-2" data-bs-toggle="modal" data-bs-target="#exampleModal" 
(click)="addClick()" 
data-backdrop="static" 
data-keyboard="false">
    Add Coffee
  </button>

It is button for showing modal. I want that button to be displayed only if user is authenticated. This is how my .ts looks like:

export class RecipeDetailsComponent implements OnInit {
  ...
  public isUserAuthenticated: boolean = false;

 ngOnInit(): void {
this.userService.authChanged
    .subscribe(res => {
      this.isUserAuthenticated = res;
    })
}

and my userService methods for checking if authenticated:

export class UserService {
  private _authChangeSub = new Subject<boolean>()
  public authChanged = this._authChangeSub.asObservable();
  
public sendAuthStateChangeNotification = (isAuthenticated: boolean) => {
    this._authChangeSub.next(isAuthenticated);
  }
  public isUserAuthenticated = (): boolean => {
    const token = localStorage.getItem("token");
 
    return token != null && this._jwtHelper.isTokenExpired(token) == false;
  }

Button appears only If i set isUserAuthenticated = true when declaring and hides if it false. I guess button reads isUserAthenticated property and show it selfs before ngOnInit. How can I delay button display till ngOnInit is resolved or just refresh after that?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If I understand your question, You're having trouble because of timing. Your code doesn't include when or how the value changes but I am guessing that the value is changed before your component initializes and therefore you are subscribing late?

If so, I recommend changing

private _authChangeSub = new Subject<boolean>()

to

private _authChangeSub = new ReplaySubject<boolean>(1);

This way, even when subscribing after the value has been emitted, the component will still receive the value. See https://www.learnrxjs.io/learn-rxjs/subjects/replaysubject

about 4 years ago · Juan Pablo Isaza 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!