问题描述
我的角度应用程序中的资产中有一个名为 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个疑问.
-
使用Http或HttpClient向本地json文件发出
POST
请求是否有效. (到目前为止,我已经使用Http而不是HttpClient完成了GET
请求,并成功获取了数据)
Is it valid to make a
POST
request to a local json file using Http or HttpClient. (Till now I have doneGET
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请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!