1. The first one

Angular supports Typescript2.9+ since 6.1+. With Typescript’s new features, we can import native JSON files directly into any Typescript module using import. To enable this new feature, perform the following steps in Angular:

Step 1.1 a

Create a JSON file anywhere in the project source directory, for example:

src/assets/json/data.json

1.2 step 2

Json file under the compilerOptions option set the following code:

{... ."compilerOptions": {... ."resolveJsonModule": true."esModuleInterop": true}}Copy the code

Among them:

  • resolveJsonModuleAllowed to import.jsonThe suffix file
  • esModuleInteropImport modules that do not export by default.jsonDocumentation is a must

1.3 step 3

Import JSON file in component/directive/service as follows:

// Your JSON file path
import data from '.. /.. /assets/json/data.json';
Copy the code

2. The second

Use Angular’s built-in httpCLient service

Step 2.1 a

Create a JSON file anywhere in the project source directory, for example:

src/assets/json/data.json

2.2 step 2

Import the httpClientModule module in the app.module.ts file as follows:

import { HttpClientModule } from '@angular/common/http';
@NgModule({
  imports: [..., HttpClientModule]
})
export class AppModule {}
Copy the code

2.3 step 3

Import JSON file from component/directive/service using httpClient:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-second-way'.template: `<div>{{jsonDataResult | json}}`
})
export class SecondWayComponent {
  jsonDataResult: any;
  
  constructor(private http: HttpClient) {
      this.http.get('assets/json/data.json').subscribe((res) = > {
        this.jsonDataResult = res;
        console.log('--- result :: '.this.jsonDataResult); }); }}Copy the code

3. The third kind

Step 3.1 a

Create a JSON file anywhere in the project source directory, for example:

src/assets/json/data.json

3.2 step 2

Create a *.d.ts file in the same directory as the JSON file, for example:

Note: you can create this file in the SRC root directory so that it can be declared globally; In addition, the file name is arbitrary, but the suffix must be.d.ts

declare module '*.json' {
  const value: any;
  export default value;
}
Copy the code

3.3 step 3

Import JSON file from component/directive/service using httpClient:

// Your JSON file path
import * as data from '.. /.. /assets/json/data.json';
// Or import like this
import data from '.. /.. /assets/json/data.json';

Copy the code

Note: If the error message does not take effect and you need to further configure the resolveJsonModule, you need to check the tsconfig.app.json configuration file in the project, including the option include, to ensure that the path of *.d.ts in the configuration, for example:

{... ."include": [
  	"src/**/*.d.ts"]}Copy the code