前后端分离时,后端接口还没有开发好的时候前端可以使用Mock根据所需造出所需数据,通过http拦截返回所需的数据
安装
1
| yarn add @delon/mock --dev
|
注册
src/app/app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import { HttpClientModule } from "@angular/common/http"; import { DelonMockModule } from "@delon/mock"; import * as MOCKDATA from "../../_mock"; import { environment } from "../environments/environment"; const MOCKMODULE = !environment.production ? [DelonMockModule.forRoot({ data: MOCKDATA })] : [] @NgModule({ imports: [ HttpClientModule, ...MOCKMODULE ] })
|
- MockOption
- data: any = ‘’ mock数据规矩
- delay: number = 300 请求延迟毫秒数
- force: boolean = false 是否强制所有请求都Mock,true 表示当请求的URL不存在时直接返回 404 错误,false 表示未命中时发送真实HTTP请求
- log: boolean = true 是否打印 Mock 请求信息,弥补浏览器无Network信息
Mock
_mock/index.ts
_mock/pai.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import { MockRequest } from "@delon/mock"; import * as Mock from "mockjs"; function getList(body) { return Mock.mock({ 'list|100': [{ 'id|+1': 1, name: '@cname', }] }) } export const APIS = { 'POST /api/list': (req: MockRequest) => getList(req.body) }
|
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import { Component, OnInit } from '@angular/core'; import { HttpClient } from "@angular/common/http"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { constructor(private _http: HttpClient) { } ngOnInit() { this._http.post('/api/list', {}).subscribe(res => { console.log('res', res); }) } }
|