我在我的角度应用程序中的资产内有一个名为fake.json的json
文件。该文件的路径是这样的。
MyApp => src =>资产=> json => fake.json
我想在应用程序文件夹内的组件中使用HttpClient向此文件发出POST
请求。
MyApp => src => app =>统计=> 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;
}
我发生了以下错误
http://localhost:4200/assets/json/fake.json的HttpErrorResponse Http失败响应:404未找到
我对此有2个疑问。
使用Http或HttpClient向本地json文件发出POST
请求是否有效。 (到目前为止,我已经使用Http而不是HttpClient完成了GET
请求,并成功获取了数据)
当文件夹中存在该文件时,为什么它返回404 Not Found。
需要帮助。
这是因为您放置在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);
});
为了从本地JSON文件读取或写入数据,可以使用json-server。
npm i json-server
。json-server --watch fake.json
。http://localhost:3000/
上请求服务器