Angular 5中从本地文件到Typescript数组的JSON数组 [英] JSON array from local file to Typescript array in Angular 5
本文介绍了Angular 5中从本地文件到Typescript数组的JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Angular 5开发Web应用程序.我有一个看起来像这样的JSON文件:
I am using Angular 5 to develop a web app. I have JSON file which looks like this:
[
{
"id": 0,
"title": "Some title"
},
{
"id": 1,
"title": "Some title"
},
...
]
此文件存储在本地.我也有一个界面:
This file is stored locally. I also have an interface:
export interface Book {
id: number;
title: string;
}
问题是我该怎么办:
- 从文件中获取数据吗?
- 根据此数据创建类型为
Book[]
的数组吗?
- Fetch the data from the file?
- Create an array of type
Book[]
from this data?
推荐答案
您可以使用import
加载文件:
import data from 'path/to/data.json';
并将其分配给类型为Book[]
的数组:
And assign that to an array of type Book[]
:
@Component({...})
class Foo {
books: Book[] = data;
}
还应在<中添加通配符模块定义. c4>告诉TypeScript编译器如何导入*.json
:
Also add a wildcard module definition in src/typings.d.ts
to tell the TypeScript compiler how to import *.json
:
declare module "*.json" {
const value: any;
export default value;
}
这篇关于Angular 5中从本地文件到Typescript数组的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文