Search code examples
angulartypescriptangular-servicesangular-ng-if

angular ng if with async data?


In my angular navbar I have a *ngIf for rather or not login/logout button should be showing

*ngIf="!authService.loggedIn()

it uses a service with this loggedIn function that returns true or false

  loggedIn() {
    return this.http.get('http://localhost:3000/users/validateToken')
      .map(res => res.json()).map(data => data.success);
  }

bu this is async, how I make my ngIf await it ? or how can I differently get the same result ?


Solution

  • Running function in the template is a bad practice. You can have a variable which is correspond for the status of the user and store the data.success there. Call your async function into the ngOnInit and assign the result to the variable.

    ngOnInit() {
       return this.http.get('http://localhost:3000/users/validateToken')
          .map(res => res.json()).subscribe(data => this.isLoggedIn = data.success);
    }
    

    And template would be like

    *ngIf="isLoggedIn"
    

    What about waiting for the response of the async function, you don't need to worry about it, if the result will come and be assigned to the variable - DI mechanism will detect that change and update the template

    Advice As I guess from the res.json() you use not an HttpClient, but Http which is deprecated. Use HttpClient and HttpClientModule.