首页 > 解决方案 > Rails 将 json 渲染到 AngularJS 前端。时间变为 00:00:00

问题描述

我正在使用 Rails 的渲染方法将渲染的 json 传递给 AngularJS 前端。日期顺利通过。当我在后端尝试puts时,渲染的 json 对象也有正确的时间。但由于某种原因,前端的时间总是变成 00:00:00。

Rails 后端代码:

... // a lot of other stuff

respond_to do |format|
  format.json do
    render json: @entries
  end
end

AngularJS 前端代码:

XXX.query(params).then((response) => {
  console.log(response);
  ...
  // a lot of other stuff
}

后端打印出的部分响应:

[{"id":101752,"version":1,"date":"2018-06-01T00:00:00.000Z","date_created":"2018-06-02T01:56:44.000Z","last_updated":"2018-06-02T01:56:44.000Z"},{"date":"2018-06-04T00:00:00.000Z","date_created":"2018-06-05T03:36:14.000Z","last_updated":"2018-06-05T03:36:14.000Z"}]

您可以看到时间戳都有时间(“日期”除外,它的时间应该是 00:00:00)。但是,当它到达前端时,所有时间戳都变成了 00:00:00。

部分响应打印在前端:

JSON响应前端打印输出.png

现在我知道解决这个问题的唯一方法是使用 strftime() 在序列化程序中为每个时间戳添加一个函数。它将时间戳转换为字符串,然后再转换为 JSON。但这将非常低效,因为我需要为每个时间戳为每个序列化程序添加 strftime() 函数。有没有人有更好的解决方案?另外,有谁知道rails渲染方法和时间戳到底发生了什么?

标签: ruby-on-railsangularjsjsonruby-on-rails-4render

解决方案


找到了解决方案。AngularJS 前端无法识别 Rails 呈现的 JSON 中的默认日期格式。在config/initializer/ams.rb文件中,您可以通过添加行来关闭标准 JSON 时间格式ActiveSupport::JSON::Encoding.use_standard_json_time_format = false。这将影响现有的前端日期时间格式,但它成功地使 AngularJS 能够识别 Rails 以 JSON 形式呈现的 TimeWithZone。


推荐阅读