Angular 6 - Load JSON from local

前端 未结 9 2462
南笙
南笙 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 04:43

    This happens because you are requesting a JSON file asynchronously, you can handle with safe navigation operator or using ngIf,

    <div class="submenu" *ngIf="linkWrite.isActive || isSubMenuWriter">
                      <span class="d-block text-right small">{{contentGeneral?.menu?.submenu?.link1?.text1}}</span>
                      <span class="d-block text-right small">{{contentGeneral?.menu?.submenu?.link1?.text2}}</span>
                    </div>
    

    or simply import the JSON file in your component and assign sampleJSON.

    import "sampleJSON" from "./sampleJSON"
    
    0 讨论(0)
  • 2020-12-14 04:45

    Create .ts file then copy contents of your json file there and add

    export const <objectName> =
    

    something like this

    export const faceProfilesSample =
    [
    {
      "id": 1,
      "depth": 0,
      "burden": null
    },
    {
      "id": 1,
      "depth": 1.97,
      "burden": 8.58
    },
    

    then you can access it by using objectName with import statement like this

    import { faceProfilesSample } from "@app/model/face-profiles-sample";
    

    No tsconfig.json changes needed

    0 讨论(0)
  • 2020-12-14 04:47

    By this way...

    import "file" from "./file.json" 
    

    I got red line and got error like module not found by angular.

    After some RND I got another way which works for me. Hope it may help someone.

    var data = require('src/file.json');
    console.log("Json data : ", JSON.stringify(data));
    
    0 讨论(0)
  • 2020-12-14 04:48

    Updated answer - Angular 5 Service to read local .json file

    In tsconfig.json

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

    0 讨论(0)
  • 2020-12-14 04:50

    Step 1: Open tsconfig.json add following lines in compilerOptions:

    "resolveJsonModule": true,
    "esModuleInterop": true
    

    Step 2: import json using following code:

    import homeData from './data.json';
    

    Note: This code is tested with Angular 9

    0 讨论(0)
  • 2020-12-14 04:53

    See this article:

    import data  from './data.json';
    export class AppComponent  {
        json:any = data;
    }
    
    0 讨论(0)
提交回复
热议问题