Using promise with observable in ionic 2 applications

698 Views Asked by At

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.

2

There are 2 best solutions below

3
On BEST ANSWER

The correct way to call an observer inside a promise and the return an observer will be like this-

return Observable.fromPromise(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();
})
5
On

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.