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 ?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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)
Oh. We forget to subscribe to the observable so the request was not made. I have updated
0

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

*ngIf="!authService.loggedIn() | async"

1 Comment

loggedIn() called infinity
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?

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.