Nikssj_
Nikssj_

Reputation: 187

Return value from subscribe in 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!

Upvotes: 1

Views: 1952

Answers (2)

Tomas Vancoillie
Tomas Vancoillie

Reputation: 3868

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

Upvotes: 3

Patricio Vargas
Patricio Vargas

Reputation: 5522

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.

Upvotes: 0

Related Questions