所以我想从这样的订阅函数返回一个值:
async obtenerListadoClases(categoria) {
var clasesDB = await this.getClases(categoria)
.subscribe((data: any) => {
clasesDB = data.clasesDB // **Want to return this**
console.log(clasesDB,'clasesDB'); // **Getting Value**
})
console.log(clasesDB, 'outside'); // **Not Getting Value**
return clasesDB;
}
此外,我想在这样的其他地方使用此功能:
var listaClases = await this.claseServicio.obtenerListadoClases(categoria); // Not getting the correct info
// console.log(listaClases , 'listado clases');
我做错了什么?或者我该如何解决?预先感谢!
答案 0 :(得分:1)
您只能订阅可观察对象。
可观察的方式
getClases(categoria): Observable<any> {
return new Observable(observer => {
// logic to return data
observer.next(data);
observer.complete()
// logic when error
observer.error(error);
});
}
返回getClases()函数
obtenerListadoClases(categoria): Observable<any>{
return this.getClases(categoria);
}
在需要的地方使用该功能:
this.obtenerListadoClases(categoria)
.subscribe(
result => {
// what you want to do with the result
},
error => {
// what you want to do with the error
});
承诺方式
getClases(categoria): Promise<any> {
return new Observable((resolve, reject) => {
// logic to return data
resolve(data);
// logic when error
reject(error);
});
}
返回getClases()函数
obtenerListadoClases(categoria): Promise<any>{
return this.getClases(categoria);
}
在需要的地方使用该功能:
this.obtenerListadoClases(categoria)
.then(result => {
// what you want to do with the result
})
.catch(error => {
// what you want to do with the error
});
答案 1 :(得分:0)
您应该在.subscribe()
中使用诺言。仅可观察者使用.subcribe()
此外,远离棱角世界中的承诺。是时候考虑被动了。
这是可观察到的吗? this.getClases(categoria)
请发布代码。