【问题标题】:How to read local JSON file in an Angular Library?如何在 Angular 库中读取本地 JSON 文件?
【发布时间】:2021-01-04 10:28:55
【问题描述】:

我正在尝试读取我正在创建的 Angular 8 库中的 JSON 文件。我想读取 JSON 文件以加载翻译并为库中的一个组件实现国际化。

附加信息: JSON 文件仅存在于 src 文件夹中,我想读取其内容并在我的服务中加载翻译。

【问题讨论】:

  • 您可以使用httpClient并拨打get(filePath/fileName.json)
  • this.http.get('./assets/data.json')
  • @kardon63 当我运行一个 Angular 应用程序时,该应用程序使用我的库中试图获取翻译的组件,我收到 404 错误。
  • @NicholasK 我收到 404 错误。我猜在库中我们没有资产,可以将它们公开在浏览器中公开可用。

标签: angular internationalization translation angular-library


【解决方案1】:

Demo写一个服务读取json,可以使用httpclient访问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);
    }

}

然后在组件中从服务中获取

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

Demo2

作为第二种方式,您可以在"compilerOptions" 中打开"resolveJsonModule": true

并像这样调用组件

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

【讨论】:

  • 我得到 404 错误,当我运行一个 Angular 应用程序时,该应用程序使用了我的库中试图获取翻译的组件。
  • 我为你添加了演示,请查看stackblitz.com/edit/…
  • 您能否为读取 json 文件的 Angular 库创建一个类似的演示,因为在库中我们没有任何公共文件夹,如“assets”文件夹。
  • 我为此添加了演示和第二种方式。你可以检查一下@TarunChopra
  • 谢谢,第二种方法对我有用。 :) 除了 Angular 库中的 json 文件之外,还有什么类似的读取文件的方法吗?
猜你喜欢
  • 2021-08-21
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
  • 2018-04-22
  • 2018-02-11
  • 2020-03-21
  • 1970-01-01
  • 2017-07-07
相关资源
最近更新 更多