Return value from subscribe in Ionic

南笙酒味 提交于 2021-01-29 10:11:56

问题


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!


回答1:


You can only subscribe to observables.

The Observable way

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

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

The Promise way

getClases(categoria): Promise<any> {
  return new Observable((resolve, reject) => {
    // logic to return data
    resolve(data);
    // logic when error
    reject(error);
  });
}

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



回答2:


You should be using promises with the .subscribe(). Only observables use .subcribe()

Also, stay away from promises in the angular world. Time to think reactive.

Is this returning an observable? this.getClases(categoria) post the code please.



来源:https://stackoverflow.com/questions/58278115/return-value-from-subscribe-in-ionic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!