环境搭建
ng new angular-demo
// 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
},
]
// tsconfig.json compilerOptions 配置 json ,否在json依赖编译失败
"resolveJsonModule": false,
typescript2.9+ import
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
// 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;
})
}
}
Es6 import in Angular offline
//src/app 下添加 json-typings.d.ts
declare module "*.json" {
const value: any;
export default value;
}
//app.component.s
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import * as data from "data.json"
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
products:any;
constructor(private http: HttpClient) {
console.log(data);
}
}
参考文献
本文作者:前端漫漫
联系邮箱:simple2012hcz@126.com
版权声明: 本文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!