简体   繁体   English

angular ng 如果有异步数据?

[英]angular ng if with async data?

In my angular navbar I have a *ngIf for rather or not login/logout button should be showing在我的 angular navbar栏中,我有一个*ngIf用于显示或不显示登录/注销按钮

*ngIf="!authService.loggedIn()

it uses a service with this loggedIn function that returns true or false它使用带有此 loggedIn function 的服务返回 true 或 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?但这是异步的,我如何让我的ngIf等待它? or how can I differently get the same result?或者我怎样才能以不同的方式获得相同的结果?

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.您可以拥有一个与用户状态相对应的变量并将data.success存储在那里。 Call your async function into the ngOnInit and assign the result to the variable.将您的异步函数调用到ngOnInit并将结果分配给变量。

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等待异步函数的响应怎么样,你不必担心,如果结果会来并分配给变量 - DI机制会检测到更改并更新模板

Advice As I guess from the res.json() you use not an HttpClient , but Http which is deprecated.建议正如我从res.json()中猜测的那样,您使用的不是HttpClient ,而是已弃用的Http Use HttpClient and HttpClientModule .使用HttpClientHttpClientModule

您可以使用async管道,因为如果请求返回一个可观察的。

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

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?工作正常......可爱的Angular......你怎么会把它推迟到只在需要时完成? Does Angular team hate promises? Angular 团队讨厌承诺吗?

You can use angularJS $timeout to get Angular to recognize a function called from async.您可以使用 angularJS $timeout获取 Angular 以识别从异步调用的 function。

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

The 50 number is a little arbitrary. 50这个数字有点武断。 It's just there as part of the $timeout function.它只是 $timeout function 的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM