There is often a need to take an HTML and then load a JSON file instead of calling the API to display the log content. By default, the current user has angular-CLI installed, so I won’t go into the details of the environment installation.
Environmental installation
MAC environment
Brew install NVM NVM install v12.16.1 NPM i-g@angular /cliCopy the code
Project creation
ng new angular-demo
Copy the code
Json file
Json files need to be placed in assets, otherwise they will not be parsed and will not be packaged with the build into Dist
/ / 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},]Copy the code
Import reads JSON
Modify the configuration in tsconfig.json configuration file
Json compilerOptions: "resolveJsonModule": true,Copy the code
Typescript2.9 + import
You need to place code in constructor
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);
}
}
Copy the code
Angular HttpClient reads JSON
// app.module.ts don't forget 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; }}})Copy the code
Once written, the file is deployed
Deploy to a static server
For example, HTTP server
npm install --global http-server
http-server -c-1 -p 8080 .
Copy the code
Deployed to tomcat
Tomcat project deployment, pay attention to the index. HTML base, not /
<base href="./" >
Copy the code