Angular 2: file not found in local .json file

I saw several different messages saying that I can’t find local files to open them, be it images or data files, but none of the solutions worked for me. I assume there is some kind of configuration that I am missing.

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

Here is what I have in app.html, PS I also use 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 tried:

 ./data/data.json data/data.json app/data/data.json 

and any other way. And they all return 404 error not found. It's like growing pains when getting to know Angular 2. Thanks in advance

+6
source share
4 answers

Previous answers said to put it directly in the www folder to make it available to the application. I would say that this is not the best solution, since the www folder is excluded when using .gitignore in the newly created Ionic2 project.

Instead, put it in the src/assets folder, and it will also be available in the application, and it will not be excluded from the git repository (by default). Then you can access using: this.http.get('assets/file.json');

You can modify the .gitignore file, but then you can include other unnecessary files.

+17
source

I did not understand that working with Ionic is that it compiles everything in the application folder and puts it in the www / build folder. Therefore, when I put the path in the folder without compilation, I did not understand that the file in which I put the path is not where I think.

So, I did two things, each worked. I put the files directly in the www file (do not put them in the assembly file, as they will be deleted every time you start the ion feed), and then correct the path accordingly. Or just fix the path, knowing that when you search for a file in your app.ts, it first needs to exit www / build.

+2
source

For anyone interested in solving the same problem. If you use the Angular CLI, and you want to make any folder accessible via http, as in this case the "data" folder.

Go to Angular -CLI.JSON, then add “folder name” which is “data” in applications -> assets

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

Can your server see the folder / data? Make sure your JSON file is in the same directory as your public / static files.

-2
source

All Articles