json - 如何在 Angular6 中从 JSON 文件获取日期值

标签 json angular typescript

我的 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/

相关文章:

java - 从大型 txt 文件中删除非 UTF-8 字符

angular - 当通过 Angular 中的 observable 从服务异步加载元素时,如何将元素添加到列表中?

javascript - Typescript 数组语法 MyModel[] 或 [MyModel]

json - Swift 结构 : handling multiple types for a single property

javascript - 通过ajax获取json数据

javascript - 将json数据放入canvas html5

javascript - angular 7 - 单选更改不显示隐藏文本

javascript - 错误类型错误 : Cannot read property '0' of undefined in angular-highcharts

angular - 使用 socket.io 模型对 Angular 5 进行单元测试

reactjs - (事件 : MouseEvent<Element, MouseEvent>) => void' 不可分配给类型 '() => Event'