Angular 2 Date deserialization

后端 未结 4 640
执念已碎
执念已碎 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:50

    I would map the string field to a date one:

    getList() : Observable<SomeModel[]> {
      return this._http.get(this._getListUrl).map(this.extractData);
    }
    
    private extractData(res: Response) {
      var data = res.json().data || [];
      data.forEach((d) => {
        d.timestamp = new Date(d.timestamp);
      });
      return data;
    }
    
    0 讨论(0)
  • 2020-12-05 07:53

    Try out my example if its work for you. And here is the docs for Date and Pipe.

    <span>Date : {{announcement.createdAt | date:'EEE, d MMM,y'}}</span>
    <span>Time : {{announcement.createdAt | date:'shortTime'}}</span>
    

    Output :

    Date : Tue, 20 Dec,2016    
    Time :  2:22 PM
    
    0 讨论(0)
  • 2020-12-05 07:53

    JSON does not provide any date specification, so it is entirely up to how it is serialized/deserialized.

    You could use reviver parameter of JSON.parse:

    this._http.get(this._getListUrl).map(res => JSON.parse(res.text(), this.reviver));
    
    reviver(key, value):any
    {
        if('timestamp' === key){
            //you can use any de-serialization algorithm here
            return new Date(value);
        }
        return value;
    }
    
    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题