简体   繁体   中英

How to read local JSON file in an Angular Library?

I am trying to read a JSON file in an Angular 8 library which I am creating. I want to read the JSON file to load translations and implement internationalization for one of the component in the library.

Additional information: The JSON file is present in the src folder only, and I want to read its content and load translations in my service.

Demo write one service to read json and you can use httpclient to reach json

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class JsonService {

  constructor(private http: HttpClient) { }
    getData(url): Observable<any> {
        return this.http.get<any>(url);
    }

}

then in component take from service

constructor(private json: JsonService ) {
    json.getData('/url').subscribe((result)=> {
      console.log(result)
    });
  }

Demo2

As a second way you can open "resolveJsonModule": true in "compilerOptions"

and call in component like

import * as employeeData from "./test.json";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM