简体   繁体   English

从文件打字稿中获取json

[英]Get json from file typescript

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 但是我收到404错误

在此输入图像描述

But I have this json file in the same folder where my service is. 但我有这个json文件在我的服务所在的文件夹中。

在此输入图像描述

What's wrong? 怎么了?

You need to give the absolute path from your base path. 您需要从基本路径中提供绝对路径。 Like, path/to/Services/client.json 比如, path/to/Services/client.json

Here's an example: https://plnkr.co/edit/60E2qb9gOjvkEAeR5CtE?p=preview 这是一个例子: https//plnkr.co/edit/60E2qb9gOjvkEAeR5CtE?p = preview

If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory 如果使用angular-cli将json文件保存在Assets文件夹(与app dir并行)目录中

In your case you need to create file like assets/client.json 在您的情况下,您需要创建像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 注意:这里你只需要在assets / client.json之类的资源文件夹中给出路径,然后你需要编写像/client.json这样的路径

If you using webpack then you need to follow above same structure inside public folder its similar like assets folder. 如果你使用webpack,那么你需要在公共文件夹中遵循相同的结构,类似于assets文件夹。

Please add this code in file the typings.d.ts 请将此代码添加到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'; 并简单地使用import * as data1 from 'path.json';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM