【问题标题】:Ajax Promise on Property not returning dataAjax Promise on Property 不返回数据
【发布时间】:2017-04-17 02:19:52
【问题描述】:

我有一个带有简单属性的 Ember 控制器,它应该从服务器获取文件列表。服务器端一切正常,数据正在返回并显示在控制台上。

在控制器中我有:

imgFiles: new Ember.RSVP.Promise(function(resolve, reject) {
                Ember.$.ajax(ENV.apiHost+'/'+ENV.apiNamespace +'/folderwalk/newsimg', {
                    success: function(response) {
                        // console.log(response);
                        resolve(response);

                    },
                    error: function(reason) {
                        reject(reason);

                    }
                });
            }),

在模板中:

{{imgFiles}}  // shows [object Object]
{{#each imgFiles as |file|}}   // doesn't loop at all
        x {{file}}
{{/each}}

我已经尝试了所有我能想到的变化。封装在函数中,返回 Promise,成功返回响应,...
我仍然无法得到返回实际数据的承诺。

【问题讨论】:

  • Still I can not get the promise to return the actual data - 承诺是对未来价值的承诺(或类似的东西) - 在您的代码中没有任何地方使用您需要的唯一功能....then - 是一个Promise 必须具有的方法,也是获得“价值”的唯一方法 - 提示:imgFiles.then(result => console.log(result)) - 将记录在 resolve(response) 解决的问题
  • 好的,谢谢!这会将其记录到控制台中。但是我怎么能退货呢?我试过.then(result => return result) 这当然给了我一个错误....
  • 恐怕我不知道如何在 ember 中正确使用 Promise - 我只能告诉你 Promise 到底是什么

标签: javascript ember.js rsvp-promise


【解决方案1】:

是的,当您记录响应时,您将获得整个有效负载。但是,Ember 不知道从服务器返回的新数据(以前是Promise)。您必须使用 set 明确告知 Ember 新数据。

  imgList: Ember.computed({
    get() {
      return new Ember.RSVP.Promise((resolve, reject) => {

        $.ajax('https://jsonplaceholder.typicode.com/photos').then((data, textStatus, jqXHR) => {
          console.log(data);
          let firstHunPhotos = data.slice(0,100);
          this.set('imgList', firstHunPhotos); // <- set the new data | set the entire data if you want!
        });
      });
    },
    set(key, value) {
        return value // <- don't forget the setter!
    }
  })

请参考这个游戏。 https://ember-twiddle.com/25d11c4c4650c18183df3595ca21f9c3?numColumns=2&openFiles=templates.application.hbs%2Ccontrollers.application.js

【讨论】:

    【解决方案2】:

    通常这些来自模型。渲染将被延迟,直到模型得到解决。

    您的案例可以以不同的方式实现。获取有关 mount/init 事件的详细信息并将解析的值设置为属性并将该属性与视图绑定。值更新后,视图将重新渲染

    【讨论】:

      猜你喜欢
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      • 2017-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多