Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using promise with observable in ionic 2 applications

I am trying to call a web service in ionic 2 application but getting struck in between promise and observable. This is my function which i am calling on click of a button-

getUserDetailsIfAccessTokenIsSuccess()


{
    this.remedyService.userGetDetail(this.loginDetailsObj.username).subscribe(
      data =>{
        console.log("userGetDetail Success="+JSON.stringify(data));
      },
      err =>{
        console.log("userGetDetail Success="+JSON.stringify(error));
        },
       () =>{
              console.log("Get Userdetails Completed");
      });
}

Now i am calling userGetDetail function in my service file.

userGetDetail(eid){
    var url = '/userGetDetail';
    var params = {
                'EID':eid
            };
    console.log(JSON.stringify(params));
    var headers = new Headers();
    this.createAuthorizationHeader(headers);
    this.storage.get('remedyAccessToken').then((value)=>{
        var token  = value.toString();
        console.log("TOKEN IN REMEDYSERVICES="+token);
        headers.append('Authorization', token);
        console.log("header value inside="+JSON.stringify(headers));
    })
    console.log("header value outside="+JSON.stringify(headers));
    let options = new RequestOptions({ headers: headers });
    this.response = this.http.post(url,this.urlEncode(params),options).map(res => res.json());
    console.log("Response JSON="+JSON.stringify(this.response));
    return this.response;
}

Now the issue is that before Authorization is getting appended to header the flow is going to next line and web api is giving error. Is there anyway i am can synchronise in such a way that after Authorization is appended then only service call should happens. I tried putting the web api call inside then block but it makes the service calls as a promise. Any help will be appreciated.

like image 247
RAHUL DEEP Avatar asked Jun 05 '26 19:06

RAHUL DEEP


1 Answers

You need to access the api inside the storage.get . This makes sure value is available when you make api call. Then convert the api call which is an Observable to promise with toPromise(). Now you can access the response as Promise . Here is an approximate workflow from your code.

this.storage.get('remedyAccessToken').then((value)=>{
    var token  = value.toString();
    console.log("TOKEN IN REMEDYSERVICES="+token);
    headers.append('Authorization', token);
    console.log("header value inside="+JSON.stringify(headers));
    console.log("header value outside="+JSON.stringify(headers));
   let options = new RequestOptions({ headers: headers });
   this.response = this.http.post(url,this.urlEncode(params),options).map(res => res.json());
   console.log("Response JSON="+JSON.stringify(this.response));
   return this.response.toPromise();
})



this.remedyService.userGetDetail(this.loginDetailsObj.username).then(fn).catch(fn);

or if you like the output to be an Observable follow this approach.

Observable.fromPromise(this.storage.get('remedyAccessToken')).flatMap((value)=>{
        var token  = value.toString();
        console.log("TOKEN IN REMEDYSERVICES="+token);
        headers.append('Authorization', token);
        console.log("header value inside="+JSON.stringify(headers));
        console.log("header value outside="+JSON.stringify(headers));
       let options = new RequestOptions({ headers: headers });
       this.response = this.http.post(url,this.urlEncode(params),options).map(res => res.json());
       console.log("Response JSON="+JSON.stringify(this.response));
       return this.response
})

This approach achieve the result you want.

like image 158
raj Avatar answered Jun 07 '26 13:06

raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!