简体   繁体   English

如何从 Angular6 的 JSON 文件中获取日期值

[英]How To Get Date Value From A JSON File in Angular6

I have a json file called data.json in my assets folder我的资产文件夹中有一个名为 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"
  }
]

Here Is my Angular service called home.service.ts这是我的名为 home.service.ts 的 Angular 服务

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

Here is my component.ts file这是我的 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);
      }
    );
  }

And this is my html file这是我的 html 文件

<div *ngFor="let project of projects">
 <h5>{{ project.project_date | date }}</h5>
</div>

The error I'm getting is:我得到的错误是:

res.text is not a function in home.service.ts

If I try it without the .map(res => JSON.parse(res.text(), this.reviver));如果我没有.map(res => JSON.parse(res.text(), this.reviver));

I get this error:我收到此错误:

Invalid argument 'December 1, 2019 at 9:03:01 AM GMT+1' for pipe 'DatePipe'

Does anyone have a solution to how I can display this on the web page as a date?有没有人可以解决如何在网页上将其显示为日期? Thanks.谢谢。

Your date should look like the following (without at ):您的日期应如下所示(没有at ):

"December 1, 2019 9:03:01 AM GMT+1"

There is no need to parse the response of your http request since it is done natively by angular无需解析 http 请求的响应,因为它是由 angular 本地完成的

getProject() {
    return this.httpService
      .get(this.projectList)

  }

To display the date using a format使用格式显示日期

{{project.project_date | date:'h:mm a z'}} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM