简体   繁体   中英

How to read Json file in TypeScript (Angular)?

I have json file en.json with content:

{
   "key": "Key"
}

How to use this file and get value by key in template:

{{ dict.key }}

I have tried:

import * as dict from 'en.json';

This is the answer to your question ( https://stackoverflow.com/a/50925032/9590251 ) if you wanna include json to app bundle itself, which is irrational.

In most cases you'll need to load it asynchronously, json is either in assets directory of the app, or remote server. But to load it you need to use either HttpModule or, preferable, HttpClientModule, ie

getJson(): Observable<MyJsonType> {
  return this.http.get<MyJsonType>('/assets/my.json');
}

Create new variable, and assign value of dict , then use that new variable in your template.

component.ts

dictObj:object= dict

template.html

<p>dictObj.key<p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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