3

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 ?

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
Anders Pedersen
  • 2,255
  • 4
  • 25
  • 49

4 Answers4

6

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.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • I tried this way, but it dosent update the loggedIn variable, it just sets it to false OnInit and never updates it. ( the navbar only getting initialized once in app.comonent.html) – Anders Pedersen Jun 06 '18 at 12:05
  • Oh. We forget to subscribe to the observable so the request was not made. I have updated – Suren Srapyan Jun 07 '18 at 07:31
0

You can use the async pipe since if request returns a observable.

*ngIf="!authService.loggedIn() | async"
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
0

Seems like

*ngIf="asyncfn() | async"

Only leads to an infinit loop, however:

constructor() {
  this.result = this.asyncFn();
}
public asyncFn() { // ... }

template:

*ngIf="result | async"

works fine... lovely Angular... how the heck would you defer it then to only done when needed? Does Angular team hate promises?

OZZIE
  • 6,609
  • 7
  • 55
  • 59
0

You can use angularJS $timeout to get Angular to recognize a function called from async.

$timeout(authService.loggedIn(), 50);

The 50 number is a little arbitrary. It's just there as part of the $timeout function.

Skhoooler
  • 71
  • 3