简体   繁体   English

从Angular 5中的本地文件到Typescript数组的JSON数组

[英]JSON array from local file to Typescript array in Angular 5

I am using Angular 5 to develop a web app. 我正在使用Angular 5开发一个Web应用程序。 I have JSON file which looks like this: 我有JSON文件,如下所示:

[
  {
        "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;
}

The questions are how do I: 问题是我如何:

  1. Fetch the data from the file? 从文件中获取数据?
  2. Create an array of type Book[] from this data? 从这个数据创建一个类型为Book[]的数组?

You could load the file with import : 您可以使用import加载文件:

import data from 'path/to/data.json';

And assign that to an array of type Book[] : 并将其分配给Book[]类型的数组:

@Component({...})
class Foo {
   books: Book[] = data;
}

demo 演示

Also add a wildcard module definition in src/typings.d.ts to tell the TypeScript compiler how to import *.json : 还要在src/typings.d.ts添加通配符模块定义 ,以告诉TypeScript编译器如何导入*.json

declare module "*.json" {
  const value: any;
  export default value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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