I am trying to work through the Angular2 tour of heroes app, and am running into bugs on the Http section of the tutorial.
At first I was getting the error:
In the tour of heroes (Angular tutorial sample) after
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data-service';
you must run the command:
ng generate service InMemoryData
Do it global install , use sudo if u have permissions problems
npm install -g angular-in-memory-web-api
to solve it, try this step
ng generate service InMemoryData --module=app
with your angular cli, then replace the code listed in the tutorial, and save it.app.module.ts
, and add some code in it, so the code like this.app.module.ts
import { HttpClientModule } from '@angular/common/http';
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';
@NgModule({
declarations: [
...
],
imports: [
...
HttpClientModule,
// The HttpClientInMemoryWebApiModule module intercepts HTTP requests
// and returns simulated server responses.
// Remove it when a real server is ready to receive requests.
HttpClientInMemoryWebApiModule.forRoot(
InMemoryDataService, { dataEncapsulation: false }
)
],
providers: [],
...
private heroesUrl = 'api/heroes'; // URL to web api
in hero.service.ts
hero.service.ts
...
export class HeroService {
constructor(
private http: HttpClient,
private messageService: MessageService,
) { }
private heroesUrl = 'api/heroes'; // URL to web api
/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
}
getHero(id: number): Observable<Hero> {
...
/** Log a HeroService message with the MessageService */
private log(message: string) {
...
ng sever
, and Enjoy!.ng generate service InMemoryData --module=app
Will create the src/app/in-memory-data.service.ts
file. Then add the code listed in the tutorial and it will work. AFAIK they don't even imply that in the tutorial so don't feel bad. In fact what they say is
The forRoot() configuration method takes an InMemoryDataService class that primes the in-memory database.
The Tour of Heroes sample creates such a class src/app/in-memory-data.service.ts
Which is gibberish and wrong.
For Angular5 tutorial and angular-in-memory-web-api@0.5.3:
Add new file "in-memory-data.service.ts" to your root directory with this contents:
import { InMemoryDbService } from 'angular-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
let heroes = [
{ id: 1, name: 'Windstorm' },
{ id: 2, name: 'Bombasto' },
{ id: 3, name: 'Magneta' },
{ id: 4, name: 'Tornado' }
];
return { heroes };
}
}
I solved this issue by running the following cmd:
$ yarn add angular-in-memory-web-api
Run this if you are using npm:
$ npm i angular-in-memory-web-api