I'm doing a web application in Angular 8.3.21. I'm trying to implemente a fake backend using InMemoryDbService to test my http requests. I'm also using faker to create random id's and words.
I have installed this:
npm install --save angular-in-memory-web-api
npm i faker --save
npm install @types/faker --save
My module:
@NgModule({
declarations: [
// A few components...
],
imports: [
HttpClientModule
environment.production ? // "forFeature" because this is a module of a feature
of my app which is loaded lazily
[] : HttpClientInMemoryWebApiModule.forFeature(
AppointmentFakeBackendService
),
],
providers: [
AppointmentService,
AppointmentFakeBackendService
]
})
The fake backend:
import {Injectable} from '@angular/core';
import {InMemoryDbService} from 'angular-in-memory-web-api';
import * as faker from 'faker/locale/es';
import {Observable} from 'rxjs';
@Injectable()
export class AppointmentFakeBackendService implements InMemoryDbService {
constructor() {
}
createDb(): {} | Observable<{}> | Promise<{}> {
const administrations = [
{id: faker.random.uuid(), administration: faker.commerce.department()},
];
return {administrations};
}
}
My service:
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {tap} from 'rxjs/operators';
@Injectable()
export class AppointmentService {
private url = 'api/administrations';
constructor(
private http: HttpClient
) {
}
getAdministrations(): Observable<any> {
return this.http.get<any>(this.url).pipe(
tap(data => console.log(data))
);
}
}
Finally, in my component I call the method from the service to get the data:
constructor(
private service: AppointmentService
) {
}
ngOnInit() {
this.service.getAdministrations().subscribe(res => {
console.log(res);
});
}
Errors:
GET http://localhost:4200/api/administrations 404 (Not Found)
What I'm missing? I have followed the official examples and I have tested solutions out there, but, didn't work for me.
I have changed this in the fake backend without success:
createDb(): {} | Observable<{}> | Promise<{}> {
const data = [
{id: faker.random.uuid(), administration: faker.commerce.department()},
];
return {administrations: data}; // <== This line
}
My goal is to create a fake backend, generating random information using faker and use a service to get the data in my component.