美文网首页
模拟数据库服务端 angular-in-memory-web-a

模拟数据库服务端 angular-in-memory-web-a

作者: 时代小召唤 | 来源:发表于2018-09-14 16:17 被阅读0次

说明

为了在没有服务端的情况下提前运行和调试angular项目,需要一个构建在内存中的模拟数据库,和对应的api

安装

npm install angular-in-memory-web-api --save

用法

  1. 创建一个类 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};
  }
}
  1. 配置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 }
    )
  ],
...
})

  1. 增删改查
地址:'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}`)

相关文章

网友评论

      本文标题:模拟数据库服务端 angular-in-memory-web-a

      本文链接:https://www.haomeiwen.com/subject/flivgftx.html