说明
为了在没有服务端的情况下提前运行和调试angular项目,需要一个构建在内存中的模拟数据库,和对应的api
安装
npm install angular-in-memory-web-api --save
用法
- 创建一个类 src/app/in-memory-data.service.ts
import { InMemoryDbService } from 'angular-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
const heroes = [
{ id: 11, name: 'Mr. 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};
}
}
- 配置app.module.ts
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';
import { HttpClientModule } from '@angular/common/http';
...
@NgModule({
....
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 }
)
],
...
})
- 增删改查
地址:'api/heroes'
新增:
this.http.post<Hero>('api/heroes', hero, httpOptions)
删除:
this.http.delete<Hero>(`api/heroes/${id}`, httpOptions)
修改:
this.http.put('api/heroes', hero, httpOptions)
查询:
this.http.get<Hero>(`api/heroes/${id}`)
网友评论