[英]Can't import local json file in angular 5
我正在嘗試導入本地文件以使用其中的數據。 我嘗試過require方法和import方法。 似乎都沒有用。 我正在使用Angular 5和Typescript 2.9.2。 我被鎖定為角度5.我正在為aot構建,當我查看導出的fesm5文件時,json文件似乎無法解析。 (我不想把它用HTTP ...)
import * as data from '../../assets/file.json';
當我嘗試將tsconfig值設置為:
"resolveJsonModule": true,
我在構建時遇到錯誤:
Cannot read property 'slice' of undefined
TypeError: Cannot read property 'slice' of undefined
at addReferencesToSourceFile (/Users/ME/Projects/PROJECT/node_modules/@angular/compiler-cli/src/transformers/compiler_host.js:520:54)
at TsCompilerAotCompilerTypeCheckHostAdapter.getSourceFile (/Users/ME/Projects/PROJECT/node_modules/@angular/compiler-cli/src/transformers/compiler_host.js:348:13)
我也嘗試過:
declare module '*.json' {
const value: any;
export default value;
}
這似乎沒有任何幫助。
還嘗試過:
declare function require(url: string);
var data = require('../../assets/file.json');
這似乎也沒有解決最終文件中的json。
您可以將您的文件放在assets文件夾下並使用來自HttpClient模塊的HTTP GET獲取它,這將返回整個json文件,在您的GET請求URL中使用您的文件路徑; 這樣的事情:
this.http.get('../assets/file.json')
.subscribe(jsonFormat => {
//Your code
});
您可以為所有GET,POST,PUT和DELETE實現創建服務。 然后在從'@ angular / common / http'導入的HttpClient的GET方法中,使用指向本地JSON文件的鏈接調用JSON。
public getAbout(): Observable<any> {
return this.http.get("./assets/json/about.json");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.