我正在Angular 8.3.21中做一个网络应用程序。我正在尝试使用InMemoryDbService实现一个假后端来测试我的 http 请求。我也faker
用来创建随机的 id 和单词。
我已经安装了这个:
npm install --save angular-in-memory-web-api
npm i faker --save
npm install @types/faker --save
我的模块:
@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
]
})
假后台:
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};
}
}
我的服务:
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))
);
}
}
最后,在我的组件中,我从服务中调用方法来获取数据:
constructor(
private service: AppointmentService
) {
}
ngOnInit() {
this.service.getAdministrations().subscribe(res => {
console.log(res);
});
}
错误:
GET http://localhost:4200/api/administrations 404(未找到)
我错过了什么?我遵循了官方示例,并且已经测试了那里的解决方案,但是对我不起作用。
我在假后端更改了这一点,但没有成功:
createDb(): {} | Observable<{}> | Promise<{}> {
const data = [
{id: faker.random.uuid(), administration: faker.commerce.department()},
];
return {administrations: data}; // <== This line
}
我的目标是创建一个伪造的后端,使用 faker 生成随机信息并使用服务来获取我的组件中的数据。