Angular 6 - Load JSON from local

前端 未结 9 2548
南笙
南笙 2020-12-14 04:26

I am trying to load a local JSONfile of two ways.

This is my json file:

{
  \"imgsesion\": \"fa_closesesion.png\",
  \"texthome\": \"volver a la home         


        
9条回答
  •  长情又很酷
    2020-12-14 05:03

    The simplest solution:

    import "myJSON" from "./myJson"
    

    Important update!

    I found, that this method stops working in newest Angular versions, because of this error:

    ERROR in src/app/app.weather.service.ts(2,25): error TS2732: Cannot find module './data.json'. Consider using '--resolveJsonModule' to import module with '.json' extension

    To make it works, go to the tsconfig.json and add this two, inside

    compilerOptions( tsconfig.json ) :

    "resolveJsonModule": true,
    "esModuleInterop": true,
    

    After change, re-run ng serve.

    If you only use the first option, you can get an error like this:

    ERROR in src/app/app.weather.service.ts(2,8): error TS1192: Module '"....app/data/data.json"' has no default export.

    (I found this very good answer here (https://www.angularjswiki.com/angular/how-to-read-local-json-files-in-angular/))

提交回复
热议问题