2017-01-20 83 views
4

获取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错误

enter image description here

但我有这json文件在我的服务相同的文件夹是。

enter image description here

有什么不对?

回答

1

您需要从基本路径给出绝对路径。如果您在使用角CLI保持资产的文件夹里面的JSON文件(平行于应用程序目录)目录

你的情况,你需要创建像资产文件https://plnkr.co/edit/60E2qb9gOjvkEAeR5CtE?p=preview

+0

如果我复制引用它的'src /应用程序/服务/客户端',如果我输入的结果是一样的。如果我在最后添加.json结果是相同的 – gsiradze

+0

@gsiradze是您的基础文件夹src? 'app/Services/client.json'如何? – echonax

+0

非常感谢。花了我5小时 – gsiradze

0

:像,path/to/Services/client.json

下面是一个例子/client.json

return this.http.get('/client.json')) 
    .map((response: Response) => { 
     console.log("mock data" + response.json()); 
     return response.json(); 
    } 
    ) 
    .catch(this.handleError); 
} 

注:在这里,你只需要给道内的资产文件夹类似资产/ client.json,那么你需要写这样/client.json

路径

如果你使用webpack,那么你需要遵循上面相同的结构在公共文件夹里的类似资产文件夹。