Angular4: how do access local json?

前端 未结 7 2201
傲寒
傲寒 2020-12-06 05:00

In Angular2 you could have a folder /data/ and a json file there and you could access it at localhost:4200/data/something.json.

This is no longer possible in Angular

7条回答
  •  抹茶落季
    2020-12-06 05:38

    Based on this post, here is complete answer for Angular 6+:

    From angular-cli doc, json can be considered as assets and accessed from standard import without use of ajax request.

    Let's suppose you add your json files into "your-json-dir" directory:

    1. add "your-json-dir" into angular.json file (:

      "assets": [ "src/assets", "src/your-json-dir" ]

    2. allow import of json modules into typings.d.ts file to prevent from typescript errors:

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

    3. in your controller/service/anything else file, simply import the file by using this relative path:

      import * as myJson from 'your-json-dir/your-json-file.json';

提交回复
热议问题