ng mock服务器数据

安装

yarn add angular-in-memory-web-api -S

src/app/app.module.ts

import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService }  from './in-memory-data.service';


@NgModule({
  imports: [
    HttpClientModule,
    
    // HttpClientInMemoryWebApiModule模块拦截HTTP请求
    //并返回模拟服务器响应。
    //当真实服务器准备好接收请求时删除它。
    HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService, {
      dataEncapsulation: false,
      delay: 1500,
    }),
  ],
})

in-memory-data.service

ng generate service InMemoryData

import { Injectable } from "@angular/core";
import { InMemoryDbService } from "angular-in-memory-web-api";

@Injectable({
  providedIn: "root",
})
export class InMemoryDataService implements InMemoryDbService {
  constructor() {}

  createDb() {
    const users = [
      { id: 11, name: "Ajanuw" },
      { 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 { users };
  }
}

使用

import { Component } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.styl"],
})
export class AppComponent {
  public users: any[] = [];

  private heroesUrl = "api/users";
  constructor(private http: HttpClient) {}

  public getUsers(): void {
    this.http.get(this.heroesUrl).subscribe((r: any[]) => {
      this.users = r;
    });
  }

  public getUser(id: number): void {
    const url = `${this.heroesUrl}/${id}`;
    this.http.get(url).subscribe(r => {
      console.log(r);
    });
  }

  public getAjanuw(): void {
    const url = `${this.heroesUrl}?name=ajanuw`;
    this.http.get(url).subscribe(r => {
      console.log(r);
    });
  }
}

html

<ul>
  <li *ngFor="let el of users; let i = index">{{ el.name }}</li>
</ul>
<button (click)="getUsers()">get user data.</button>
<hr />
<button (click)="getUser(11)">get user</button>

<hr />
<button (click)="getAjanuw()">get Ajanuw</button

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...