Tuesday, July 18, 2017

a better posting on getting Observables back out of Observable shapes on the TypeScript side so that you may do stuff with them

In order to force an Observable to a .toPromise() like this some stuff has to happen upstream. In your service where you make a rest call, craft something like so:

public findFoo(matchManyGuid: string): Observable<Array<MyDto>> {
   var url = "http://www.example.com/api/foo/" + matchManyGuid;
   return this.http.get(url).map(response => this.mildParsing(response));
}

 
 

Alright, we need ._body off the Response and for some reason I don't yet understand we cannot have at it with type safety in the way so we have to have a hack like this to cast a Response to an any.

protected mildParsing(r:any) {
   let parsing = JSON.parse(r._body, function(key,value){
      return value;
   });
   return parsing;
}

 
 

Finally, get what you want where you call the service:

this.myService.findFoo(someGuid).toPromise()
   .then(function(data){
      let foo: Array<MyDto> = data;
      console.log(foo);
   },function(error){
      console.log(error);
   });

No comments:

Post a Comment