Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 278
discodane Avatar asked May 13 '16 15:05

discodane


People also ask

Where is Angular JSON file located?

The angular. json file is always found in the root folder of a CLI generated project, along with the package. json file.

How do I install a local JSON file?

Answer: Use the jQuery $. getJSON() Method You can simply use the $. getJSON() method to load local JSON file from the server using a GET HTTP request. If the JSON file contains a syntax error, the request will usually fail silently.


2 Answers

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.

like image 193
Gabe O'Leary Avatar answered Sep 21 '22 06:09

Gabe O'Leary


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.

like image 42
discodane Avatar answered Sep 24 '22 06:09

discodane