Search code examples
angularangular2-services

angular tutorial could not receive data from http call


I am trying to learn Angular 2 by following the Tutorial Step 7 HTTP (https://angular.io/tutorial/toh-pt6). However the function getHeroes() in hero.service.ts still return nothing.

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

where the mock service is implemented from InMemoryDbService.

Any idea please?


Solution

  • the HTTP client will fetch and save data from the in-memory web API InMemoryDbService. Basically, it means that InMemoryDbService will simulate your server that will receive HTTP request and will respond to them.

    Did you install the module in-memory-web-api? If not, you can install it: npm install --save angular-in-memory-web-api.

    Don't forget to import the module in your app.module (this import should come only after the import of HttpModule):

    imports: [
        ...
        HttpModule,
        InMemoryWebApiModule.forRoot(InMemoryDataService),
        ...
      ],
    

    Also, a new change introduce in the new api of in-memory-web-api no longer wraps the HTTP response in the data property (github). So it should be response.json() instead of response.json().data.