【问题标题】:404 when requesting json file with Angular http使用 Angular http 请求 json 文件时出现 404
【发布时间】:2017-06-05 20:57:33
【问题描述】:

我的服务中有此代码

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 angular typescript


    【解决方案1】:

    您需要提供基本路径的绝对路径。喜欢,path/to/Services/client.json

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

    【讨论】:

    • 如果我复制引用它是`src/app/Services/client',如果我输入结果是一样的。如果我在最终结果中添加 .json 是一样的
    • @gsiradze 是您的基本文件夹 src? app/Services/client.json 怎么样?
    • @gsiradze 很高兴我能帮上忙 :-)
    【解决方案2】:

    如果您使用 angular-cli 将 json 文件保存在 Assets 文件夹(与应用程序目录平行)目录中

    在您的情况下,您需要创建像 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 之类的 assets 文件夹中提供路径,然后你需要编写 /client.json 之类的路径

    如果你使用 webpack,那么你需要在 public 文件夹中遵循上面相同的结构,它类似于 assets 文件夹。

    【讨论】:

      【解决方案3】:

      请将此代码添加到文件 typings.d.ts

      declare module "*.json"
      { const value: any;
        export default value;
      }
      declare module "json!*"
      { const value: any;
        export default value;
      }
      

      然后使用import * as data1 from 'path.json';简单地导入

      【讨论】:

        猜你喜欢
        • 2018-05-27
        • 2020-09-16
        • 2017-06-23
        • 2014-11-20
        • 2013-08-25
        • 2013-06-19
        • 1970-01-01
        • 2019-10-06
        • 1970-01-01
        相关资源
        最近更新 更多