ng mock server data

installation

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

generate a 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 };
  }
}

use

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

Guess you like

Origin www.cnblogs.com/ajanuw/p/11833894.html