【问题标题】:POST request to a local json file using HttpClient使用 HttpClient 向本地 json 文件发送 POST 请求
【发布时间】:2019-07-19 15:11:58
【问题描述】:

我的 Angular 应用程序的资产中有一个名为 fake.jsonjson 文件。这个文件的路径是这样的。

MyApp => src => assets => json => fake.json

我想在 app 文件夹内的组件中使用 HttpClient 向该文件发出 POST 请求。

MyApp => src => app => Statistics => statistics.component.ts

组件源代码

export class StatisticsComponent {

  persons: Person[];

  options = {
    sDom: 'rt<"bottom"p>',
    pagingType: 'full_numbers',
    pageLength: 10,
    serverSide: true,
    processing: true,
    ajax: (dataTablesParameters: any, callback) => {
      this.http
        .post<DataTablesResponse>(
          './../../assets/json/fake.json',
          dataTablesParameters, {}
        ).subscribe(resp => {
          this.persons = resp.data;
          callback({
            recordsTotal: resp.recordsTotal,
            recordsFiltered: resp.recordsFiltered,
            data: []
          });
        });
    },
    columns: [
      { data: "id" },
      { data: "firstName" },
      { data: "lastName" }
    ]
  };

  constructor(private http: HttpClient) {

  }

}

class Person {
  id: number;
  firstName: string;
  lastName: string;
}

class DataTablesResponse {
  data: any[];
  draw: number;
  recordsFiltered: number;
  recordsTotal: number;
}

我发生了以下错误

HttpErrorResponse http://localhost:4200/assets/json/fake.json 的 Http 失败响应:404 Not Found

我对此有两个疑问。

  1. 使用 Http 或 HttpClient 向本地 json 文件发出 POST 请求是否有效。 (到目前为止,我已经使用 Http 而不是 HttpClient 完成了GET 请求并成功获取数据)

  2. 为什么当文件存在于文件夹中时它返回 404 Not Found。

需要帮助。

【问题讨论】:

标签: angular angular-httpclient


【解决方案1】:

这是因为您放入 assets 文件夹中的任何内容都将通过 GET 请求提供。您可以通过在浏览器上导航到http://localhost:4200/assets/json/fake.json 来测试它。如果要测试POST方法,需要启动一个服务器。

HttpModule 在更高版本的 Angular 中已被弃用和删除。你应该把它改成HttpClientModule

要使用HttpClient 对其进行测试,您可以执行以下操作。

HttpClientModule 添加到您的AppModule

在你的组件中注入HttpClient

constructor(private httpClient: HttpClient) {}

并按如下方式提出请求

this.httpClient.get('/assets/json/fake.json',  { observe: 'body' })
    .subscribe(result => {
      console.log(result);
    });

【讨论】:

    【解决方案2】:

    为了从本地 JSON 文件读取或写入数据,您可以使用 json-server。

    1. 创建 fake.json 文件。
    2. 安装json-servernpm i json-server
    3. 启动 JSON 服务器json-server --watch fake.json
    4. 现在在http://localhost:3000/上请求服务器

    点击文档链接:https://www.npmjs.com/package/json-server

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多