我的 Assets 文件夹中有一个名为 data.json 的 json 文件
[
{
"id": 1,
"project_name": "X project",
"project_date": "December 1, 2019 at 9:03:01 AM GMT+1",
"project_status": "vip",
"rating": "5 star"
}
]
这是我的 Angular 服务,名为 home.service.ts
projectList = '../../../assets/data.json';
getProject() {
return this.httpService
.get(this.projectList)
.map(res => JSON.parse(res.text(), this.reviver));
}
reviver(key, value): any {
if ('project_date' === key) {
return new Date(value);
}
return value;
}
这是我的 component.ts 文件
projects: string[];
showProject() {
this.homeservice.getProject().subscribe(
data => {
this.projects= data as string[];
console.log(this.projects);
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
}
这是我的 html 文件
<div *ngFor="let project of projects">
<h5>{{ project.project_date | date }}</h5>
</div>
我收到的错误是:
res.text is not a function in home.service.ts
如果我在没有 .map(res => JSON.parse(res.text(), this.reviver)); 的情况下尝试它;
我收到此错误:
Invalid argument 'December 1, 2019 at 9:03:01 AM GMT+1' for pipe 'DatePipe'
有谁知道如何在网页上将其显示为日期的解决方案吗?谢谢。
最佳答案
您的日期应如下所示(不带 at
):
"December 1, 2019 9:03:01 AM GMT+1"
无需解析 http 请求的响应,因为它是由 Angular 本地完成的
getProject() {
return this.httpService
.get(this.projectList)
}
使用 format 显示日期
{{project.project_date | date:'h:mm a z'}}
关于json - 如何在 Angular6 中从 JSON 文件获取日期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57624346/