Angular 2: file not found on local .json file

2019-04-06 18:23发布

I have seen a few different posts about not being able to find local files to open them up whether they be images or data files, but none of the solutions have worked for me. My guess would be there is some configuration I'm missing.

The file I'm looking for is in a folder named "data" on the same level as my app.html and app.ts files.

Here is what I have in app.html, PS I'm also using Ionic2:

<ion-menu (click)='getDepartments()' side='right' type='overlay' [content]="content">

and in the app.ts file I have:

getDepartments() {
    this.http.get('/data/data.json')
        .map(res => res.json())
        .subscribe(
            data => this.departments = data,
            err => console.log(err),
            () => console.log('Random Quote Complete')
        );
}

I've tried:

./data/data.json

data/data.json

app/data/data.json

and any other path. And they all return a 404 file not found error. This seems just like growing pains with getting familiar with Angular 2. Thanks in advance

4条回答
我想做一个坏孩纸
2楼-- · 2019-04-06 18:36

For any anyone who is interested in resolving the same problem. If you are using Angular CLI and you want to make any folder accessible through http as in this case "data" folder.

Go to Angular-CLI.JSON then add "the folder name" which is "data" under apps -> assets

"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico",
        "data"
      ],

查看更多
老娘就宠你
3楼-- · 2019-04-06 18:42

Previous answers have said to put it directly in the www folder to make it available to the app. I would say this is not the best solution as the www folder is excluded using .gitignore in a newly created Ionic2 project.

Instead put it inside the src/assets folder and it will also be made available in App and it will NOT be excluded from the git repo (by default). Then you can access using: this.http.get('assets/file.json');

You could modify the .gitignore file, but then you may be including other unnecessary files.

查看更多
Viruses.
4楼-- · 2019-04-06 18:42

I didn't realize that working with Ionic that it compiles everything in the app folder and puts it into the www/build folder. Therefore when I put a path in the uncompiled app folder I didn't realize that the file I'm putting the path in isn't where I think it is.

So I did two things, each worked. I put the files directly in the www file (don't put them in the build file as they will be deleted every time you run ionic serve), and then fix the path accordingly. Or just fix the path knowing that when you look for a file in your app.ts, it needs to exit out of www/build first.

查看更多
混吃等死
5楼-- · 2019-04-06 18:51

Is your server able to see the folder '/data'? Make sure your JSON file is located in the same directory as your public/static files.

查看更多
登录 后发表回答