简体   繁体   English

(Typescript) 将 json 导入 Angular 4 项目

[英](Typescript) Import json into Angular 4 project

I have a json file of translations that I want to use in my angular 4 project.我有一个 json 翻译文件,我想在我的 angular 4 项目中使用它。 The file is also used in php which is why it needs to be stored as json rather than as a js module.该文件也在 php 中使用,这就是为什么它需要存储为 json 而不是 js 模块的原因。

It has this structure有这个结构

export interface IDictionary {
    amsterdamCenter: number[];
    amsterdamBounds: Array<number[]>;
    prices: Price[];
    cuisines: Object;
    areas: Object;
}

Followinghttps://hackernoon.com/import-json-into-typescript-8d465beded79 I have changed typings.d.ts to readhttps://hackernoon.com/import-json-into-typescript-8d465beded79之后,我已将 Typings.d.ts 更改为阅读

/* SystemJS module definition */
declare var module: NodeModule;
interface NodeModule {
  id: string;
}

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

Now I have an error with现在我有一个错误

import * as dictionary from './dictionary.json';

export const Dictionary: IDictionary = dictionary;

[ts] Type 'typeof " .json"' is not assignable to type 'IDictionary'. [ts] 类型 'typeof " .json"' 不能分配给类型 'IDictionary'。 Property 'amsterdamCenter' is missing in type 'typeof " .json"'.类型“typeof“ .json””中缺少属性“amsterdamCenter ”。

However然而

export const Dictionary: any = dictionary;

does work.确实有效。 I'm hoping there is an incantation of TS that will permit me to import typescript using my interfaces我希望有一个 TS 咒语可以让我使用我的接口导入打字稿

@simon-h try this code. @simon-h 试试这个代码。 Its working fine它的工作正常

import * as dictionary from './dictionary.json';

export const Dictionary: IDictionary = (<any>dictionary);

(or) (或者)

export const Dictionary: any = (<any>dictionary);

(or) (或者)

export const Dictionary: any = dictionary as any;

One thing you could do is parse the Json file like :您可以做的一件事是解析 Json 文件,例如:

import * as myJson from './my-json.json';

getMyJson(): Array<any> {
 return JSON.parse(JSON.stringify(myJson))
}

you can type the response to a specific model/class if you wish.如果您愿意,您可以键入对特定模型/类的响应。

EDIT: Actually just import and assign, copy if you wish:编辑:实际上只需导入和分配,如果您愿意,请复制:

import * as settingsMenu from './settings-menu.json';
const array = settingsMenu;
// OPTIONAL: copy object
const menu: Array<BdbMap> = new Array();
Object.assign(menu, array);

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

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