Get json from typescript file

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 call it:

this.client = this.clientsService.getClient()
  .subscribe(data => {
    console.log(data);
  });

But I get 404 error

enter image description here

But I have this jsonfile in the same folder where my service is located.

enter image description here

What happened?

+4
source share
2 answers

You need to specify the absolute path from the base path. For instance,path/to/Services/client.json

Here is an example: https://plnkr.co/edit/60E2qb9gOjvkEAeR5CtE?p=preview

+1
source

If you use angular-cli Store the json file in the "Resources directory" folder (in parallel with dir).

In your case, you need to create a 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);
}

: , assets/client.json, , /client.json

webpack, , .

0

Source: https://habr.com/ru/post/1667388/


All Articles