Angular `ngOnInit` 中的异步/等待 [英] async/await in Angular `ngOnInit`

查看:57
本文介绍了Angular `ngOnInit` 中的异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在评估替换 Angular 的利弊.RxJS 的 Observable 带有简单的 Promise 以便我可以使用 asyncawait 并获得更直观的代码风格.

I’m currently evaluating the pros ‘n’ cons of replacing Angular’s resp. RxJS’ Observable with plain Promise so that I can use async and await and get a more intuitive code style.

我们的典型场景之一:在 ngOnInit 中加载一些数据.使用 Observables,我们可以:

One of our typical scenarios: Load some data within ngOnInit. Using Observables, we do:

ngOnInit () {
  this.service.getData().subscribe(data => {
    this.data = this.modifyMyData(data);
  });
}

当我从 getData() 返回一个 Promise 并使用 asyncawait 时,它变成:

When I return a Promise from getData() instead, and use async and await, it becomes:

async ngOnInit () {
  const data = await this.service.getData();
  this.data = this.modifyMyData(data);
}

现在,很明显,Angular 不会知道",ngOnInit 变成了 async.我觉得这不是问题:我的应用程序仍然像以前一样工作.但是当我查看 OnInit 接口时,该函数显然没有以表明它可以声明为 async 的方式声明:

Now, obviously, Angular will not "know", that ngOnInit has become async. I feel that this is not a problem: My app still works as before. But when I look at the OnInit interface, the function is obviously not declared in such a way which would suggest that it can be declared async:

ngOnInit(): void;

所以——底线:我在这里做的事情合理吗?或者我会遇到什么不可预见的问题?

So -- bottom line: Is it reasonable what I’m doing here? Or will I run into any unforseen problems?

推荐答案

这与您之前的方案没有什么不同.ngOnInit 将返回一个 Promise 并且调用者将忽略该承诺.这意味着调用者在继续之前不会等待方法中的所有内容完成.在这种特定情况下,这意味着视图将完成配置,并且视图可能会在 this.data 设置之前启动.

It is no different than what you had before. ngOnInit will return a Promise and the caller will ignore that promise. This means that the caller will not wait for everything in your method to finish before it proceeds. In this specific case it means the view will finish being configured and the view may be launched before this.data is set.

这和你之前遇到的情况一样.调用者不会等待您的订阅完成,并且可能会在 this.data 填充之前启动应用程序.如果您的视图依赖于 data,那么您可能有某种 ngIf 设置来阻止您访问它.

That is the same situation you had before. The caller would not wait for your subscriptions to finish and would possibly launch the app before this.data had been populated. If your view is relying on data then you likely have some kind of ngIf setup to prevent you from accessing it.

我个人并不认为这是一种尴尬或不好的做法,只要您了解其中的含义即可.但是, ngIf 可能很乏味(无论哪种方式都需要它们).我个人已经开始在有意义的地方使用路由解析器,这样我就可以避免这种情况.在路线完成导航之前加载数据,我可以在加载视图之前知道数据可用.

I personally don't see it as awkward or a bad practice as long as you're aware of the implications. However, the ngIf can be tedious (they would be needed in either way). I have personally moved to using route resolvers where it makes sense so I can avoid this situation. The data is loaded before the route finishes navigating and I can know the data is available before the view is ever loaded.

这篇关于Angular `ngOnInit` 中的异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆