码迷,mamicode.com
首页 > 其他好文 > 详细

ng mock服务器数据

时间:2019-11-11 12:31:06      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:service   sel   pcl   ice   psu   exp   createdb   creat   tornado   

安装

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

ng mock服务器数据

标签:service   sel   pcl   ice   psu   exp   createdb   creat   tornado   

原文地址:https://www.cnblogs.com/ajanuw/p/11833894.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!