从文件打字稿中获取json

我的服务中有这个代码

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);
  }
}

在我的组件中,我称之为:

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

但是我收到404错误

《从文件打字稿中获取json》

但我有这个json文件在我的服务所在的文件夹中.

《从文件打字稿中获取json》

怎么了?

最佳答案 您需要从基本路径中提供绝对路径.比如,path / to / Services / client.json

这是一个例子:https://plnkr.co/edit/60E2qb9gOjvkEAeR5CtE?p=preview

点赞