借助In-Memory Web API,Angular应用的HttpClient发送请求之后,会自动被In-memory
Web API拦截,在in-memory数据存储器中管理,并返回模拟的数据响应。
After installing the module, the app will make requests to and receive responses from the HttpClient without knowing that the In-memory Web API is intercepting those requests, applying them to an in-memory data store, and returning simulated responses.
安装方法:使用下面的命令行:
npm install angular-in-memory-web-api --save
9秒钟就完成了安装:
Angular In-memory Web API使用介绍运行时的调试
在app module里导入:
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';
并添加到NgModule的imports区域内:
Angular In-memory Web API使用介绍运行时的调试
目前还缺少一个in-memory-data.service,
Angular In-memory Web API使用介绍运行时的调试
使用下列的命令行生成:
ng generate service InMemoryData
Angular In-memory Web API使用介绍运行时的调试
inMemoryData service的实现代码:
import { Injectable } from '@angular/core';
import { InMemoryDbService } from 'angular-in-memory-web-api';
import { Hero } from './heroes/hero';
@Injectable({
providedIn: 'root',
})
export class InMemoryDataService implements InMemoryDbService {
createDb() {
const heroes = [
{ id: 11, name: 'Dr Nice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' }
];
return {heroes};
}
// Overrides the genId method to ensure that a hero always has an id.
// If the heroes array is empty,
// the method below returns the initial number (11).
// if the heroes array is not empty, the method below returns the highest
// hero id + 1.
genId(heroes: Hero[]): number {
return heroes.length > 0 ? Math.max(...heroes.map(hero => hero.id)) + 1 : 11;
}
}
在hero service里,通过构造函数参数注入http client:
Angular In-memory Web API使用介绍运行时的调试
定义一个私有属性:
private heroesUrl = ‘api/heroes’; // URL to web api