ember.js - How to access a JSON file in my controller
问题描述
In my Ember app, I have a JSON file filled with data in my public directory (I.E. public/data/articles.json
.
I have an article route where I would like to load in this data and display it in the front-end. How could I do this successfully? I am willing to use the model hook, however I don't know of a solution off-hand.
I currently have the following code in my controller. However, this doesn't work (most likely because the data is loaded in after it is rendered).
import Controller from '@ember/controller';
import $ from 'jquery';
export default Controller.extend({
init() {
this._super(...arguments);
$.getJSON("/data/articles.json", function (data) {
console.log("test");
console.log(data);
this.articleData = data;
}
})
解决方案
你可以直接写return $.getJSON("/data/articles.json");
在你的路由model
钩子中,然后像model
在你的模板/控制器中一样访问数据。
更优雅的是使用fetch
:
async model() {
const res = await fetch('/data/articles.json');
return res.json();
}
推荐阅读
- html - 向右浮动使文本看起来更小
- go - Golang 中的原子和并发安全 Redis 事务
- python - 如何使用 Scipy 和一维数组正确重塑 N 维插值的值?
- java - 如何从java中的txt文件中读取两个矩阵
- java - Flyway:Java 迁移的前缀
- c# - 需要帮助将 OpenXML dataValidation 添加到现有 Excel 文件
- java - 文件上传 windows Java selenium
- php - Laravel 注销,添加监听器
- wordpress - 使用 WP_Query 按发布日期排序的帖子不包括年份
- ios - 当用户停止按下按钮时如何运行代码?