本文介绍了使用HttpClient向本地json文件POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的角度应用程序中的资产中有一个名为 fake.json json文件.该文件的路径是这样的.

I have one json file named fake.json inside assets in my angular application. Path of this file is like this.

我想在应用程序文件夹内的组件中使用HttpClient向此文件发出POST请求.

I want to make a POST request to this file using HttpClient in my component which is in inside app folder.

组件源代码

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

我发生了以下错误

针对 http://localhost:4200/assets/json的Http错误响应/fake.json :找不到404

HttpErrorResponse Http failure response for http://localhost:4200/assets/json/fake.json: 404 Not Found

对此我有2个疑问.

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

  1. Is it valid to make a POST request to a local json file using Http or HttpClient. (Till now I have done GET request using Http not HttpClient and got the data successfully)

当文件夹中的文件存在时为什么返回404 Not Found.

Why it returns 404 Not Found when the file is present there inside the folder.

需要帮助.

推荐答案

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

It's because whatever you put inside assets folder will be served via GET requests. You can test this by simply navigation to http://localhost:4200/assets/json/fake.json on browser. If you want to test POST method, you need to start a server.

HttpModule在更高版本的Angular中已被弃用并删除.您应该将其更改为HttpClientModule

HttpModule is deprecated and removed in later versions of Angular. You should change it to HttpClientModule

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

To test it with HttpClient, you can do the following.

HttpClientModule添加到您的AppModule

在组件中注入HttpClient

constructor(private httpClient: HttpClient) {}

并按照以下步骤进行请求

And make the request as follows

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

这篇关于使用HttpClient向本地json文件POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:16