Angular(14) - 从服务端获取数据 - 官方教程英雄指南之添加模拟服务器 (详细解说)

1 加入HTTP服务

src/app/app.module.ts (
  • 导入服务
import { HttpClientModule }    from '@angular/common/http';
@NgModule({
  imports: [
    HttpClientModule,
  ],
})

2 模拟数据服务器

  • 2.1 安装官方模拟服务器
npm install angular-in-memory-web-api --save
  • 2.2
src/app/app.module.ts
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService }  from './in-memory-data.service';
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 }
)

3 ### 创建 InMemoryData 组件, 通过服务提供数据

ng generate service InMemoryData
import { Injectable } from '@angular/core';
import { InMemoryDbService } from 'angular-in-memory-web-api';
import { Hero } from './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;
  }
}

总结,到此,我们的模拟服务器就安装好了,下节我们讲一下如何在服务中使用HTTP

posted @ 2020-08-20 14:07  三重罗生门  阅读(303)  评论(0编辑  收藏  举报