1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Did you add the module to your import dependencies in app.module.ts?
i did add InMemoryWebApiModule.forRoot(InMemoryDataService),
Does the other functions of your hero.service.ts work or is getHeroes the only one that doesn't?
it is working if using response.json() instead of response.json().data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.