Load json from local file with http.get() in angular 2

前端 未结 7 1163
情歌与酒
情歌与酒 2020-11-29 00:38

I\'m trying to load a local json with http.get() in angular 2. I tried something, that I found here on stack. It looks like this:

this is my app.m

7条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 01:28

    For Angular 5+ only preform steps 1 and 4


    In order to access your file locally in Angular 2+ you should do the following (4 steps):

    [1] Inside your assets folder create a .json file, example: data.json

    [2] Go to your angular.cli.json (angular.json in Angular 6+) inside your project and inside the assets array put another object (after the package.json object) like this:

    { "glob": "data.json", "input": "./", "output": "./assets/" }

    full example from angular.cli.json

    "apps": [
        {
          "root": "src",
          "outDir": "dist",
          "assets": [
            "assets",
            "favicon.ico",
            { "glob": "package.json", "input": "../", "output": "./assets/" },
            { "glob": "data.json", "input": "./", "output": "./assets/" }
          ],
    

    Remember, data.json is just the example file we've previously added in the assets folder (you can name your file whatever you want to)

    [3] Try to access your file via localhost. It should be visible within this address, http://localhost:your_port/assets/data.json

    If it's not visible then you've done something incorrectly. Make sure you can access it by typing it in the URL field in your browser before proceeding to step #4.

    [4] Now preform a GET request to retrieve your .json file (you've got your full path .json URL and it should be simple)

     constructor(private http: HttpClient) {}
            // Make the HTTP request:
            this.http.get('http://localhost:port/assets/data.json')
                     .subscribe(data => console.log(data));
    

提交回复
热议问题