首页 > 解决方案 > 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.js

解决方案


为了完整起见,我将在这里介绍两种执行此操作的方法,一种使用 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'),

一旦模型解析,这将自动更新为标题。


推荐阅读