一 初步调通
npm install -g json-server
新建 mocks/data.json 放到根目录一级
{"family":{
"grandFathers": [
{
"id":1,
"name":"jack-grandFather"
},
{
"id":2,
"name":"tom-grandFather"
}
],
"fathers": [
{
"id":1,
"name":"jack-father",
"grandFatherId":1
},
{
"id":2,
"name":"tom-father",
"grandFatherId":2
}
],
"sons": [
{
"id":1,
"name":"jack",
"fatherId":1
},
{
"id":2,
"name":"tom",
"fatherId":2
}
]
}
}
修改package.json
"mock:server": "json-server --watch mocks/data.json",
启动
npm run mock:server
二 代理:我们不需要3000 我们需要4200!
根目录创建proxy.conf.json
proxy.conf.json
{
“/fathers”: {
“target”: “http://localhost:3000",
“secure”: false
}
}
package.json
"start:proxy": "ng serve — proxy-config proxy.conf.json"
运行命令
npm run start:proxy
此时 访问http://localhost:4200/fathers和访问http://localhost:3000/fathers是一样的
三 安装 concurrently
npm install concurrently --save-dev
package.json
"start:proxy:mock:server": "concurrently — kill-others \"npm run mock:server\" \"npm run start:proxy\""
运行命令
npm run start:proxy:mock:server
这样 我们既有了一个mock数据库,又可以通过4200的路由来访问相关数据了。
四 拆分数据
理由:因为现实世界的数据是非常多的 所以我们不应该把所有数据写到一个json中
npm install json-concat --save-dev
建立mocks/concat-json.js
var jsonConcat = require('json-concat');
jsonConcat({
src: "mocks", //文件夹目录
dest: "mocks/dt.json", //生成文件
}, function(json){
console.log(json);
});
package.json
"concat:mocks": "node \"./mocks/concat-json.js\"",
运行命令
npm run concat:mocks
就把所有mocks下的json全部打入到dt.json中了
那么我们就可以这样做了
创建data文件夹
将data.json放入并创建另两个json
通过命令打到dt.json中
修改proxy.conf.json 指向api
代码如下
dog.json
{
"dog":{
"name":"mikey",
"age":2,
"voice":"wolfwolf"
}
}
cat.json
{
"cat":{
"name":"mimi",
"age":3,
"voice":"miumiu"
}
}
proxy.conf.json
{
"/family": { "target": "http://localhost:3000", "secure": false},
"/dog": {"target": "http://localhost:3000","secure": false},
"/cat": {"target": "http://localhost:3000","secure": false}
}
concat-json.js
var jsonConcat = require('json-concat');
jsonConcat({
src: "mocks/data", //文件夹目录
dest: "mocks/data.json", //生成文件
}, function(json){
console.log(json);
});
运行命令
npm run concat:mocks //生成json
npm run start:proxy:mock:server //运行
这样我们就分离了不同的json,在运行的时候合并他们并给了他们不同的api
多级路径api
如果我们希望要
http://localhost:4200/1/dog 访问dog数据
则
修改proxy.conf.json
"/1/dog": {"target": "http://localhost:3000/dog","secure": false}
如果我们希望要
http://localhost:4200/a/b/c/cat 访问cat数据
则
修改proxy.conf.json
"/a/b/c/cat": {"target": "http://localhost:3000","secure": false,"pathRewrite": {"/a/b/c/cat":"/cat"}}