I have this code in my service
import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
import {Client} from "../clients/client";
import {Observable} from "rxjs/Observable";
@Injectable()
export class ClientsService {
private clientUrl = './client.json';
private headers = new Headers({ 'Accept': 'application/json' });
private options = new RequestOptions({ headers: this.headers });
private client : Client;
constructor(private http:Http) {}
getClient() : Observable<any>{
return this.http.get(this.clientUrl, this.options)
.map(res => res);
}
}
and in my component I'm calling it:
this.client = this.clientsService.getClient()
.subscribe(data => {
console.log(data);
});
But I'm getting 404 error
But I have this json
file in the same folder where my service is.
What's wrong?
You need to give the absolute path from your base path. Like, path/to/Services/client.json
Here's an example: https://plnkr.co/edit/60E2qb9gOjvkEAeR5CtE?p=preview
If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory
In your case you need to create file like assets/client.json
return this.http.get('/client.json'))
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
Note: here you only need to give path inside assets folder like assets/client.json then you need to write path like /client.json
If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.
Please add this code in file the typings.d.ts
declare module "*.json"
{ const value: any;
export default value;
}
declare module "json!*"
{ const value: any;
export default value;
}
and simply import using import * as data1 from 'path.json';
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.