前端analysis | What,Why,Who,When,Where,How

《angular8》- angular本地json文件读取的2中方法

2020-10-31

常有这样的需求,一个html,然后加载json文件,替代调用api,展示日志内容。
默认当前用户已安装angular-cli,就不具体的介绍环境安装了。

环境安装

mac环境下

1
2
3
brew install nvm 
nvm install v12.16.1
npm i -g @angular/cli

项目创建

1
ng new angular-demo

json文件

json文件,需要放置在assets目录中,否则解析不到,也不会随构建打包到dist中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// assets/data.json 
[
{
"letter": "A",
"frequency": 0.08167
},
{
"letter": "B",
"frequency": 0.01492
},
{
"letter": "C",
"frequency": 0.02782
},
{
"letter": "D",
"frequency": 0.04253
},
{
"letter": "E",
"frequency": 0.12702
},
]

import方式读取json

tsconfig.json配置文件中修改配置

1
2
// tsconfig.json compilerOptions 配置 json ,否在json依赖编译失败
"resolveJsonModule": true,

typescript2.9+ import

需要放置code位于constructor中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import * as data from '../assets/data.json';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
products:any;

constructor(private http: HttpClient) {
const res = (data as any).default;
console.log(res);
}
}

Angular HttpClient 读取json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// app.module.ts 别忘了imports HttpClientModule 
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';


@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
products:any;

constructor(private http: HttpClient) {
this.http.get('assets/data.json').subscribe(data =>{
console.log('data....',data);
this.products = data;
})
}
}

编写完毕后,文件部署

部署到静态服务器

譬如 http-server

1
2
npm install --global http-server
http-server -c-1 -p 8080 .

部署到tomcat

tomcat项目部署,需要注意index.html中base,非/

1
<base href="./" > 

使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏