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

查看:1026
本文介绍了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,而调用方将忽略该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天全站免登陆