【发布时间】:2020-02-12 20:22:20
【问题描述】:
我在尝试从 http 服务获取 ngOnInit 中的数据时遇到问题。当组件被触发时,我需要在 var 中设置我的数据,以便我可以在其他函数中使用它。
我通过执行异步 ngOnInit 并接收来自 Promise 函数的响应来实现这一点,但我认为这不是一个好习惯吗?我该如何改进它?
这是我的代码:
COMPONENT.TS
async ngOnInit() {
this.username = localStorage.getItem('username');
this.segment.value = 'FUNCIONAL';
this.categoria = this.segment.value;
this.listadoClases = await this.claseServicio.obtenerListadoClases(this.categoria); // **Need to set this variable at onInit**
SERVICE.TS
getClases(actividad) {
return this.http.get(`https://anders-test.herokuapp.com/clases/obtenerPorCategoria/${actividad}`);
}
obtenerListadoClases(categoria) {
return new Promise(resolve => {
this.getClases(categoria).subscribe(data => {
if (data) {
resolve(data)
}
})
})
}
我这样做是因为我试图学习/理解异步/等待。我想稍微升级一下我的代码..但是在阅读了很多之后我没有得到这个想法..
提前谢谢大家!
【问题讨论】:
-
基本上没问题,虽然有一种更简单的方法可以将 observable 转换为 promise:只需
return this.getClases(cetegoria).toPromise()。
标签: angular ionic-framework service async-await