【问题标题】:Return value from subscribe in IonicIonic 中订阅的返回值
【发布时间】:2019-10-07 22:52:55
【问题描述】:

所以我想从订阅函数中返回一个值,如下所示:

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');

我做错了什么?或者我该如何解决?提前致谢!

【问题讨论】:

  • 请贴出getClases()函数的代码

标签: return observable ionic4 subscribe


【解决方案1】:

您只能订阅 observables

可观察的方式

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 Promise((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
 }); 

【讨论】:

    【解决方案2】:

    您应该使用带有.subscribe() 的承诺。只有 observables 使用 .subcribe()

    另外,远离 Angular 世界中的承诺。是时候思考被动了。

    这是返回一个可观察的吗? this.getClases(categoria)请贴代码。

    【讨论】:

    • async obtenerListadoClases(categoria): Promise { return await this.getClases(categoria) .subscribe((data: any)=>{ }) },顺便说一句,我在 Ionic 4 上
    • 是的 ionic 使用 Angular。您应该将您承诺的回报转换为可观察的 pudes 用户of de rxjs
    猜你喜欢
    • 2017-07-14
    • 1970-01-01
    • 2019-12-09
    • 2018-09-04
    • 2021-09-22
    • 1970-01-01
    • 2021-07-16
    • 2021-09-06
    • 2021-04-27
    相关资源
    最近更新 更多