Angular 2 Date deserialization

后端 未结 4 649
执念已碎
执念已碎 2020-12-05 07:27

I have an Angular 2 application. A service is requests data from an api that returns the results like the following:

{
    \"data\":[
        {\"id\":1,\"ti         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 07:57

    The date pipe only accepts Date values not string values.

    See How to get Date object from json Response in typescript for how to convert dates in JSON.

    Alternatively you can create your own string-to-date conversion pipe

    @Pipe({name: 'toDate'})
    export class StringToDate implements PipeTransform {
      transform(value, [exponent]) : number {
        if(value) {
          return new Date(value);
        }
      }
    }
    

    and then use it like

    {{item.timestamp |toDate | date:'short'}}
    

    Hint: don't forget to add the pipe to pipes: [StringToDate] on the @Component(...) decorater where you want to use it.

    See also

    • https://github.com/angular/angular/pull/8038
    • https://github.com/angular/angular/pull/7794

提交回复
热议问题