相关疑难解决方法(0)

使用Angular 4.3 HttpClient解析日期

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

this.http.get<Person> (url).subscribe(...)
Run Code Online (Sandbox Code Playgroud)

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

使用旧的Http我在调用JSON.parse()时使用了reviver函数:

this.http.get(url)
  .map(response => JSON.parse(response.text(), this.reviver))
Run Code Online (Sandbox Code Playgroud)

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

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

  return value;
}
Run Code Online (Sandbox Code Playgroud)

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

json date angular angular-httpclient

23
推荐指数
5
解决办法
2万
查看次数

标签 统计

angular ×1

angular-httpclient ×1

date ×1

json ×1