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, {
delay: 100,
passThruUnknownUrl: true, // 应将无法识别的请求URL传递到原始后端,避免和其他库冲突
dataEncapsulation: false, // 是否使用 {data: ...}
}),
],
})
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
可以模拟delete
await this.http.delete('/api/users/11').toPromise();
console.log(await this.http.get('/api/users').toPromise());
如果你想想用delete删除数据
await this.http.post('api/users/delete', { id: 11 }).toPromise()
export class InMemoryDataService implements InMemoryDbService {
constructor() {}
createDb(reqInfo?: RequestInfo): {} | Observable<{}> | Promise<{}> {
const users = [...];
return {
users,
};
}
post(reqInfo?: RequestInfo) {
switch (reqInfo.collectionName) {
case 'users':
if (reqInfo.id === 'delete') {
const userId = reqInfo.utils.getJsonBody(reqInfo.req).id;
reqInfo.collection.splice(
reqInfo.collection.findIndex((it) => it.id == userId),
1
);
return {
status: 200,
body: {},
};
}
default:
break;
}
}
}
还有login
console.log( this.http.post('api/login', this.loginForm.value).toPromise() );
@Injectable({
providedIn: 'root',
})
export class InMemoryDataService implements InMemoryDbService {
constructor() {}
createDb(reqInfo?: RequestInfo): {} | Observable<{}> | Promise<{}> {
// ...
}
post(reqInfo?: RequestInfo) {
switch (reqInfo.collectionName) {
case 'login':
return reqInfo.utils.createResponse$(() => {
const { req } = reqInfo;
const body = reqInfo.utils.getJsonBody(req);
if (body.username === 'admin' && body.password === '123') {
return {
status: 200,
body: {
token: `token ${body.username}`,
},
};
}
return {
status: 401,
body: {},
};
});
default:
break;
}
}
}
使用Mack.js返回假数据
import { Injectable } from '@angular/core';
import { InMemoryDbService, RequestInfo } from 'angular-in-memory-web-api';
import { Observable } from 'rxjs';
import * as Mock from 'mockjs';
@Injectable({
providedIn: 'root',
})
export class InMemoryDataService implements InMemoryDbService {
constructor() {}
createDb(reqInfo?: RequestInfo): {} | Observable<{}> | Promise<{}> {
return Mock.mock({
'users|20': [
{
'id|+1': 1,
username: '@name',
avatar: '@image(100x100, @color)',
},
],
});
}
}