angular6 使用mockjs模拟后台数据

文章目录

    • 问题描述
    • 环境安装
    • 定义mock数据文件
    • main.ts 中引入 mockjs模拟的数据
    • 测试

问题描述

由于后台没有开发完成,因此需要前端根据模拟数据先做界面开发,为了方便http请求异步联调,想使用mockjs的请求功能,方便开发

环境安装

cnpm install -S mockjs

定义mock数据文件

import Mock from "mockjs";

//拦截请求,返回假数据
Mock.mock("http://10.91.7.159:9080/taxloan/productStat?customerId=sdf", {
  message: "调用成功",
  data: [
    { name: "XXXX1", code: "P00003" },
    { name: "XXXX2", code: "P00028" },
    { name: "XXXX3", code: "P00002" },
    { name: "XXXX4", code: "P00003" }
  ],
  rtn: "0"
});

main.ts 中引入 mockjs模拟的数据

// 如果允许mock数据
if (environment.isMock) {
  import('./assets/data/mockData').then(_ => {
    console.log('引入mock数据成功')
  })
}

测试

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

@Component({
  selector: 'app-examination-paper',
  templateUrl: './examination-paper.component.html',
  styleUrls: ['./examination-paper.component.scss']
})
export class ExaminationPaperComponent implements OnInit {

  constructor(public http:HttpClient) { }

  ngOnInit(): void {
    let urlStr:string = 'http://10.91.7.159:9080/taxloan/productStat?customerId=sdf'
    this.http.post(urlStr, {}).subscribe(response => {
      console.log(response);
    });
  }

}

你可能感兴趣的:(angular6,ionic4,typescript,rx)