Get Subscribe Data out of function

Can I get the value of the get subscribe data out of the function?

 getPartners() {
      this.http.get('http://www.cinemairis.it/wp-json/wp/v2/partners').subscribe(data => {
      this.items = JSON.parse(data['_body']).results;
      this.loading.dismiss();
    },
      error => {
        console.log(error);
   }
   return this.items

);

Can i get the value of this.item? i try but this value is undefined

Try that :wink:

 getPartners() {
        this.http.get('http://www.cinemairis.it/wp-json/wp/v2/partners')
            .subscribe((data: Response) => {
                this.items = data.json().body.results;
                this.loading.dismiss();
            },
            (error: any) => {
                console.log(error);
            });
            return this.items
    }

what object is data?

image

import { Http, Response } from ‘@angular/http’;

Thank You for your support!

I resolve with this

  getPartners() {
    return new Promise(resolve => {
      this.http.get('http://www.cinemairis.it/wp-json/wp/v2/partners')
        .subscribe(data => {
          this.itemspartners = JSON.parse(data['_body']).results;
          resolve(this.itemspartners);
        });
    });

but I can’t get data from this:

if I use for example var results = getPartners()

i have this object:

How i get the value from this?

image

I change my code

getPartners() {
    return new Promise(resolve => {
      this.http.get('http://www.cinemairis.it/wp-json/wp/v2/partners')
        .map(results => results.json())
        .subscribe(data => {
          this.itemspartners = data;
          resolve(this.itemspartners);
        });
    });

  openPartners(item) {
    this.getPartners().then(data => {
      console.log(data);
    })
  }

and now i have this:
image

How I get the value from this object?

For example if i write data.length in openPartners(item) i have an error

1 Like

Let’s back up here. When dealing with asynchronous programming, there are, generally speaking, two kinds of functions:

Type 1: they do what they’re going to do when they do it, and everybody else just has to deal with the fact that they don’t know when it’s been done. They must return void.

Type 2: they return a future and anybody who calls them must only attempt to access the result once the future has resolved. Almost always, the first word you type in these functions should be “return”.

You can go either way here, but you don’t want to be instantiating needless promises.

Option 1:

getPartners(): void {
  this.http.get('http://www.cinemairis.it/wp-json/wp/v2/partners').finally(() => {
    // we do this here so that the loading gets dismissed when errors happen as well
    this.loading.dismiss();
  }).subscribe((rsp) => {
    this.items = rsp.json().results;
  }, (err) => {
  });
}

You should probably initialize this.items to a reasonable default (such as an empty array) if you are using it the way people typically do (such as backing an ngFor), or you will get template errors.

Option 2:

getPartners(): Observable<Partner[]> {
  return this.http.get('http://www.cinemairis.it/wp-json/wp/v2/partners').map((rsp) => {
    return rsp.json().results;
  });
}

If you go this route, any place you actually need the results, you must subscribe to the return value of getPartners:

getPartners().subscribe((partners) => {
  // only in here is the data available
});
3 Likes

Thank You :slight_smile:

getData() {
    this.httpClient.get('url').subscribe(
      data => {
        this.incomingdata = data as any[];   // FILL THE ARRAY WITH DATA.
      },
     
    );
    return this.incomingdata; //how can I return above data here
  }

i have also same problem ,how can i use" this.incomingdata" out side of the function

get function is asynchronous, so:

this.incomingdata = data as any[]; 

ends after:

return this.incomingdata;

So you have to work with Promise:

return new Promise((resolve, reject) => {
      this.http.get('........')
        .subscribe(
         data => {
          resolve(data)
        },
         error => {
          reject(error);
        },
);
    });

And in your controller:

getData().then(data => {
      console.log(data);
//do here what you want
    })
2 Likes

great thank’s Pasto92 a lot :yum::yum::yum::yum::yum:

i use with laravel and ionic 4

getData()
.then(data=>{
this.listitems = data[‘data’]
// or you can use this.listitems = data.data <— but error when compile t0 ionic cordova run android
})

I resolved it with this:

1- Getting data:

      xmarkSolicitud(idTran:string, stagePos:string){
        let urlEndPoint=this.urlApi+idTran+'/stages/'+stagePos+'/mark';
//Creating the promise
        return new Promise((resolve, reject) => {
            this.http.post(urlEndPoint,'',{headers:this.headers}).subscribe(
                res=>{
                  console.log('Mark Transaction OK, idTransac='+idTran);
                  resolve(res); //value to return out of the promise
                },(err: HttpErrorResponse)=>{
                  reject(err); //returning Error
                  console.log(err.error);
                  console.log(err.name);
                  console.log(err.message);
                  console.log(err.status);
                }
              );
        });//end Promise
      }//end xmarktype or paste code here

2- Using the data:


       this.medService.xmarkSolicitud('617163c535e03f82a19daeaf73e5547c','0').then(resp=>{
       console.log(resp);
//make your stuff with the response (resp)
     }, error=>{
//manage error
       console.log(error);
     });

It’s horror to transform an observable like http to a promise as observables are supercharged promises :grinning:, so U r downgrading gold to brass

But if u insist, why not use the toPromise() operator after the http (in a pipe) to save a few lines?

1 Like