ruby-on-rails - 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。
部分响应打印在前端:
现在我知道解决这个问题的唯一方法是使用 strftime() 在序列化程序中为每个时间戳添加一个函数。它将时间戳转换为字符串,然后再转换为 JSON。但这将非常低效,因为我需要为每个时间戳为每个序列化程序添加 strftime() 函数。有没有人有更好的解决方案?另外,有谁知道rails渲染方法和时间戳到底发生了什么?
解决方案
找到了解决方案。AngularJS 前端无法识别 Rails 呈现的 JSON 中的默认日期格式。在config/initializer/ams.rb
文件中,您可以通过添加行来关闭标准 JSON 时间格式ActiveSupport::JSON::Encoding.use_standard_json_time_format = false
。这将影响现有的前端日期时间格式,但它成功地使 AngularJS 能够识别 Rails 以 JSON 形式呈现的 TimeWithZone。
推荐阅读
- python - TypeError:转换时无法将 IntervalArray 转换为 dtype float64(pd.qcut,x)
- python-3.x - 为什么当 app.config["USE_X_SENDFILE"] 设置为 True 时,swagger 在浏览器中不显示任何内容?
- java - Sonarqube Maven 错误不在 git 树内
- html - 导航栏无法使用 bootstrap5 在移动设备上扩展
- arrays - 通过添加相邻元素使所有元素相等所需的最小步骤
- elasticsearch - Elasticsearch 无痛脚本更新并进行一次 POST 调用
- javascript - [call] 方法如何与 Vue JS 中的类组件一起使用?
- salesforce - 如何将值从 Lightning Web 组件传递到流变量?
- jquery - Datatable 的界面无法正常工作
- javascript - 有没有办法使用 h.264 编解码器恢复实时 h264 播放(客户端重新加入)?