为什么我的 Ember 组件中的 .then() 中没有 'this' 上下文

Why Don't I have 'this' context inside of a .then() in my Ember component

我是 Ember 的新手。

这是我的组件的代码:

import Ember from 'ember';

export default Ember.Component.extend({
  profiles: Ember.inject.service(),
  tagName: 'td',
  classNames: ['grey'],
  classNameBindings: ['unreadMessages'],
  unreadMessages: null,

onInit: function() {
    const id = this.get('conversation.id');
    return this.get('profiles').getMessages(id)
      .then(function(bool) {
        this.set('unreadMessage', bool);
      });
  }.on('init')
});

这抛出:

TypeError: Cannot read property 'set' of undefined

所以我可以收集到我没有需要在 .then()

中调用 this.setthis 上下文

我需要将 return this.get('profiles').getMessages(id) 的结果分配给组件中的 unreadMessages 属性。这样我就可以将它用于 classNameBinding

这是我从服务调用的方法

  getMessages(id){
    return this.get('ajax').request('/messages?id=' + id)
    .then((obj) => {
      const unreadMessages = obj.messages.filter((e) => e.read === false);

      if (unreadMessages === []) {
         return false;
      } else {
         return true;
      }
    });
  }

我只能访问其 .then() 中的 getMessages returns 的布尔值,而我无法在 [=17= 中调用 this.set() ] 我正在寻找解决方法。我认为我已经接近并且正在努力,因为我缺乏 Ember.

的经验

getMessages 向我的后端发出 'GET' 请求并过滤消息以检查是否有任何未读消息,然后 returns 判断真假。 classNameBinding 的目的是通知用户他们是否有该线程的任何未读消息。这是我为练习而构建的一个非常简单的电子邮件风格的消息传递应用程序。

谢谢!

改变

onInit: function() {
    const id = this.get('conversation.id');
    return this.get('profiles').getMessages(id)
      .then(function(bool) {
        this.set('unreadMessage', bool);
      });
  }.on('init')
});

onInit: function() {
    const id = this.get('conversation.id');
    return this.get('profiles').getMessages(id)
      .then((bool) => {
        this.set('unreadMessage', bool);
      });
  }.on('init')
});

这里的问题是,当您在 then 中写入 function(){} 时,范围会发生变化,并且 this 不会引用组件 this。 这就是为什么在 ES6 中引入词法 this 的概念。这将保留 this。所以改用箭头函数,它会很顺利地工作..