从Ionic订阅返回值 [英] Return value from subscribe in Ionic

查看:61
本文介绍了从Ionic订阅返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想从这样的订阅函数返回一个值:

So I want to return a value from a subscribe function like this:

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;
  }

此外,我想在另一个地方使用此功能:

Also, I want to use this function in another place like this:

 var listaClases = await this.claseServicio.obtenerListadoClases(categoria); // Not getting the correct info
  //  console.log(listaClases , 'listado clases');

我做错了什么?或者我该如何解决?预先感谢!

What Im doing wrong? Or how can I fix it? Thanks in advance!

推荐答案

您只能订阅可观察对象.

可观察的方式

getClases(categoria): Observable<any> {
  return new Observable(observer => {
    // logic to return data
    observer.next(data);
    observer.complete()
    // logic when error
    observer.error(error);
  });
}

返回getClases()函数

Return the getClases() function

obtenerListadoClases(categoria): Observable<any>{
  return this.getClases(categoria);
}

在需要的地方使用该功能:

Use the function where you want:

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()函数

Return the getClases() function

obtenerListadoClases(categoria): Promise<any>{
  return this.getClases(categoria);
}

在需要的地方使用该功能:

Use the function where you want:

this.obtenerListadoClases(categoria)
 .then(result => {
   // what you want to do with the result
 })
 .catch(error => {
   // what you want to do with the error
 }); 

这篇关于从Ionic订阅返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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