[英]Import Json file in Angular 6?
尝试了几种不同的方法来导入 json 文件但得到
countries.json has unknown extension.
有没有解决我失踪的问题?
当前的 tsconfig:
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"types": [ "node"],
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
]
},
"include": ["./src/**/*", "./src/**/*.json"],
}
这里的导入如下import * as countries from './countries.json';
和国家的设置。json 是这个..
[
{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
]
我相信 Angular 6 json 支持有点不稳定,所以我会将项目更新到更新的版本(使用 angular,工作量不是很大)。 从 Angular 7 开始,您可以像这样配置 tsconfig.json 文件:
{
"compileOnSave": false,
"compilerOptions": {
...
"resolveJsonModule": true,
...
}
这样你就可以像这样导入你的 .json 文件:
import * as data from './data.json';
希望这可以帮助!
我会一步一步地留下一个例子: https://www.techiediaries.com/import-local-json-files-in-typescript/
import something from "somewhere"
意味着从路径导入默认导出值。
显然, json
文件默认没有任何导出。 您可以导入所有内容,也可以从中导入一些属性。
要从 json 文件导入所有内容:
import * as something from "somewhere"
从 json 文件导入一些属性:当文件的内容像
文件.json
{
"name": "Stackoverflow",
"otherProperty": "otherValue"
}
仅导入name
:
import { name } from "file.json"
但是Typescript
在2.9
版本中添加了--resolvejsonmodule
选项。 据我所知 Angular 在版本7
开始使用Typescript 2.9
,所以对于你的情况:
json.service.ts
@Injectable()
export class JsonService {
constructor(private http: HttpClient) {}
getJson(path: string) {
return this.http.get(path);
}
}
并且不要忘记将您的JsonService
添加到模块的providers
数组中,最后,您需要在模块中导入HttpClientModule
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.