Parse date with Angular 4.3 HttpClient

后端 未结 5 929
再見小時候
再見小時候 2020-12-14 01:20

I\'m currently switching to the new HttpClient of Angular 4.3. One advantage is that I can specify a type info on the GET method and that the returned JSON is parsed into th

5条回答
  •  长情又很酷
    2020-12-14 01:28

    This works for me:

    import { Injectable } from '@angular/core';
    import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse, HttpResponse } from '@angular/common/http';
    import { Observable } from 'rxjs/Observable';
    
    @Injectable()
    export class ApiInterceptor implements HttpInterceptor {
      private dateRegex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)$/;
    
      private utcDateRegex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/;
    
      constructor() { }
    
      intercept(request: HttpRequest, next: HttpHandler): Observable> {
        return next.handle(request)
          .do((event: HttpEvent) => {
            if (event instanceof HttpResponse) {
              this.convertDates(event.body);
            }
          });
      }
    
      private convertDates(object: Object) {
        if (!object || !(object instanceof Object)) {
          return;
        }
    
        if (object instanceof Array) {
          for (const item of object) {
            this.convertDates(item);
          }
        }
    
        for (const key of Object.keys(object)) {
          const value = object[key];
    
          if (value instanceof Array) {
            for (const item of value) {
              this.convertDates(item);
            }
          }
    
          if (value instanceof Object) {
            this.convertDates(value);
          }
    
          if (typeof value === 'string' && this.dateRegex.test(value)) {
            object[key] = new Date(value);
          }
        }
      }
    }
    

    The advantage of this over the answer of bygrace is that you don't need to parse to json yourself, you just convert the dates after angular is done with the parsing.

    This also works with arrays and nested objects. I modified this it should support arrays.

提交回复
热议问题