简体   繁体   中英

Angular 2: file not found on local .json file

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

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.

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.

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" ], 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM