【问题标题】:Angular 4.4 Date deserialization from REST-Service来自 REST-Service 的 Angular 4.4 日期反序列化
【发布时间】:2018-04-02 08:57:40
【问题描述】:

我正在使用 Angular 4 的新 HttpModule 从 REST 服务中检索数据。问题是,数据包含一个 Date 类型的属性。我见过this thread,但是当我尝试线程中建议的解决方案时,我收到以下错误:res.json is not a function

这是我的代码:

getMarkets(): Observable<Christmasmarket[]> {
    let markets: Christmasmarket[];
    return this.http.get(this.apiUrl).map(this.extractData);

  }

  private extractData(res: Response) {

    let body = res.json().data;
    console.log(body);
    body.forEach((d) => {
      d.start = new Date(d.start)
      d.end = new Date(d.end);
    });
    return body.data || {};
  }

这是来自服务的数据:

[
  {
    "id": 1,
    "name": "mein markt1",
    "start": "2017-11-14T23:00:47.838+0000",
    "end": "2017-12-14T23:00:47.838+0000",
    "postalCode": "1100",
    "city": "wien",
    "address": "test",
    "rating": 4.56,
    "ratingPrice": 1.2,
    "numberOfRatings": 10,
    "latLng": {
      "latitude": 48.208982,
      "longitude": 16.373213
    },
    "openingHours": [
      {
        "open": true,
        "start": 600,
        "end": 1200,
        "dayOfWeek": 0
      },
      {
        "open": true,
        "start": 660,
        "end": 1200,
        "dayOfWeek": 1
      },
      {
        "open": true,
        "start": 690,
        "end": 1200,
        "dayOfWeek": 2
      },
      {
        "open": true,
        "start": 600,
        "end": 1200,
        "dayOfWeek": 3
      },
      {
        "open": true,
        "start": 600,
        "end": 1200,
        "dayOfWeek": 4
      },
      {
        "open": true,
        "start": 600,
        "end": 1200,
        "dayOfWeek": 5
      },
      {
        "open": true,
        "start": 600,
        "end": 1200,
        "dayOfWeek": 6
      }
    ],
    "extraordinaryOpeningHours": [

    ]
  }
]

【问题讨论】:

    标签: json angular typescript


    【解决方案1】:

    您可能使用的是新的HttpClientModule,而不是旧的HttpModule。使用HttpClient,JSON 的反序列化是自动完成的,所以没有response.json() 方法。

    更多关于它的角度文档:https://angular.io/guide/http

    另外注意HttpClient,你可以指定响应的接口,所以它会自动为你映射:

    interface ItemsResponse {
      results: string[];
    }
    
    http.get<ItemsResponse>('/api/items').subscribe(data => {
      // data is now an instance of type ItemsResponse, so you can do this:
      this.results = data.results;
    });
    

    我猜这也适用于Date 类型。

    【讨论】:

    • 是的,谢谢,我不太明白 extractData 现在也将我的类型作为参数。谢谢!
    • 您实际上错过的是您根本不需要 extractData 方法 - HttpClient 会为您完成。
    • @GreyBeadedGekk 我在没有 extractData 函数的情况下尝试过,不,它不起作用。不知何故,它没有将其映射为日期。当我调用 start.getTime() 时,我收到一个错误,即没有这样的函数 - 因为它是一个字符串。
    猜你喜欢
    • 2016-08-09
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多