1

I'm following the Angular tutorial at https://angular.io/tutorial/toh-pt6 which shows how to retrieve a Json response from an API call, and then match that to a promise.

The specific example is:

getHeroes(): Promise<Hero[]> {
  return this.http.get(this.heroesUrl)
         .toPromise()
         .then(response => response.json().data as Hero[])
         .catch(this.handleError);
}

I'm using the AWS API gateway, the use of which is detailed at http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-generate-sdk-javascript.html

Being new to both Typescript and promises, how do I modify the sample method to fit into the structure of the Angular tutorial?

apigClient.methodName(params, body, additionalParams)
    .then(function(result){
      // Add success callback code here.
    }).catch( function(result){
      // Add error callback code here.
    });

In my example, result.data is an array of JSON objects.

Evonet
  • 3,600
  • 4
  • 37
  • 83
  • Do you need to use the JavaScript SDK for API Gateway? Can you just use the API Gateway URL? This will allow you to to simply use `http.get(url)` like the Heroes example. – Mark Jul 23 '17 at 06:09
  • Need to use the SDK as I'm also using Cognito and it handles all the header signing – Evonet Jul 23 '17 at 06:14
  • @Evonet I watched Vasco of Angular University explaining Typescript. I think you may find some of his sampler videos on Youtube... In his videos he shows how Typescript is transcompiled into regular Javascript, (because Javascript, not Typescript is what browsers understand). It comes in handy to do a code comparison and work out what the '=>' fat arrow is doing. Maybe someone else can shed some light how he does that.. Because most of the code I see is going through things like Webpack/and using polyfill in my projects and it's not so simple to see the way Vasco had his environment setup. – JGFMK Jul 23 '17 at 06:51
  • Unrelated to this specific question there's a great answer to other use cases of the operator here that clarified some stuff for me.. https://stackoverflow.com/a/34274626/495157 – JGFMK Jul 23 '17 at 06:53
  • 1
    @Evonet BTW, I stumbled upon on how to show transcompiled code.. Here's the link http://www.typescriptlang.org/play/ – JGFMK Jul 26 '17 at 22:33

1 Answers1

2

You should create a Promise wrapper as below for your Client API call -

getResult(): Promise<any> {
  return new Promise((resolve, reject) => {
     apigClient.methodName(params, body, additionalParams)
     .then(function(result){
       resolve(result)
     }).catch( function(result){
       reject(result)
     });
  })
}
Ashvin777
  • 1,446
  • 13
  • 19
  • I'll give that a go - does it go inside my getHeroes function? – Evonet Jul 23 '17 at 06:48
  • Yes the getResult is same as getHeroes, make sure you use the proper typings because getHeroes returns Promise, but in this case it is JSON so try the typings -> getHeroes: Promise for now. – Ashvin777 Jul 23 '17 at 06:51