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
I found that the simplest way to achieve this is by adding the file.json under folder: assets.
No need to edit: .angular-cli.json
Service@Injectable()
export class DataService {
getJsonData(): Promise{
return this.http.get('http://localhost:4200/assets/data.json').toPromise();
}
}
Componentprivate data: any[];
constructor(private dataService: DataService) {}
ngOnInit() {
data = [];
this.dataService.getJsonData()
.then( result => {
console.log('ALL Data: ', result);
data = result;
})
.catch( error => {
console.log('Error Getting Data: ', error);
});
}
Ideally, you only want to have this in a dev environment so to be bulletproof. create a variable on your environment.ts
export const environment = {
production: false,
baseAPIUrl: 'http://localhost:4200/assets/data.json'
};
Then replace the URL on the http.get for ${environment.baseAPIUrl}
And the environment.prod.ts can have the production API URL.
Hope this helps!