4

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

enter image description here

But I have this json file in the same folder where my service is.

enter image description here

What's wrong?

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

if I copy reference it's `src/app/Services/client' and If I enter that result is same. If I add .json at the end result is same
@gsiradze is your base folder src? How about app/Services/client.json ?
@gsiradze Glad I could help :-)
0

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.

Comments

0

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';

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.