ember.js - Controller values not available to template after $.ajax success in Ember
问题描述
After much frustration with ember data, I'm trying a simpler approach to fetching & displaying data in Ember. I use $.ajax() to load data in a controller and update the controller's title property. This works. However, the template never updates. It displays 'Old Value'.
What needs to be done to make the template see the new value?
I'm working with Ember 3.1
// controllers/index.js
import Controller from '@ember/controller';
export default Controller.extend({
title:'Old Value',
getData: $.ajax(
{
type: "GET",
url:"https://jsonplaceholder.typicode.com/posts/1",
success: function(data) {
console.log("success", data);
this.title = data.title;
console.log("title: ", this.title); // logs new value: 'sunt aut fac..'
}
}
)
});
template
// templates/index.hbs
<h1>this is the index route</h1>
<h3>Title is: {{title}}</h3>
解决方案
为了完整起见,我将在这里介绍两种执行此操作的方法,一种使用 ember-data,另一种没有。首先没有。
Ember 控制器在生命周期钩子方面几乎没有灵活性,尤其是与组件相比。但是,您可以在此处使用 init 方法来解决此问题。例如,您可以像这样重写上面的内容:
init() {
this._super(...arguments);
$.ajax({
type: 'GET',
url: 'https://jsonplaceholder.typicode.com/posts/1',
success: data => this.set('title', data.title),
});
},
在这种情况下,您有一个正确的引用,this
并且您的请求将在应用程序加载时发出(与您当前的实现相同)。
现在要使用 ember-data 执行此操作,我们只需将以下内容添加到您的路由中:
model() {
return $.ajax({
type: 'GET',
url: 'https://jsonplaceholder.typicode.com/posts/1',
});
},
这将作为控制器模型返回 ajax 请求的结果。因此,在控制器中,我们只是为我们期望的数据设置别名。
import { alias } from '@ember/object/computed';
...
title: alias('model.title'),
一旦模型解析,这将自动更新为标题。
推荐阅读
- android - 如何将对象从函数传递到android中的oncreate方法
- arrays - 如何在scala中创建这样的矩阵?
- android - 如何获取对 ViewModel 的引用
- reactjs - 如何将以下 HOC 实现转换为 react 钩子实现
- vue.js - 如何从 vue 中的 ag-grid 获取显示行数据?
- c++ - 小字符串优化(调试与发布模式)
- c# - 在 Blazor 页面上检索自定义 Blazor 组件的所有实例
- c# - 如何控制 C# 中“抛出异常”窗口中显示的消息?
- r - 在所有行中更改值,但最高
- amazon-s3 - 使用 terraform .12.10+ 模板文件函数将 local_secrets 填充到 s3 存储桶