使用 Angular 4.3 HttpClient 解析日期 [英] Parse date with Angular 4.3 HttpClient

查看:29
本文介绍了使用 Angular 4.3 HttpClient 解析日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在切换到 Angular 4.3 的新 HttpClient.一个优点是我可以在 GET 方法上指定类型信息,并将返回的 JSON 解析为给定的类型,例如

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 the given type, e.g.

this.http.get<Person> (url).subscribe(...)

但不幸的是,JSON 中的所有日期在结果对象中都被解析为数字(可能是因为 Java 日期对象在后端被序列化为数字).

But unfortunately, all dates in the JSON are parsed as numbers in the resulting object (probably because the Java Date objects are serialized as numbers in the backend).

使用旧的 Http 我在调用 JSON.parse() 时使用了一个 reviver 函数,如下所示:

With the old Http I used a reviver function when calling JSON.parse() like this:

this.http.get(url)
  .map(response => JSON.parse(response.text(), this.reviver))

在 reviver 函数中,我从数字创建了日期对象:

and in the reviver function I created date objects from the numbers:

reviver (key, value): any {
  if (value !== null && (key === 'created' || key === 'modified'))
    return new Date(value);

  return value;
}

新的 HttpClient 是否有类似的机制?或者在解析 JSON 时进行转换的最佳做法是什么?

Is there a similar mechanism with the new HttpClient? Or what is the best practice to do conversion when the JSON is parsed?

推荐答案

这对我有用:

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<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request)
      .do((event: HttpEvent<any>) => {
        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);
      }
    }
  }
}

这个比bygrace的答案的优势在于你不需要自己解析为json,你只需在 angular 解析完成后转换日期即可.

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.

这篇关于使用 Angular 4.3 HttpClient 解析日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆