服务中的功能没有返回正确的值

时间:2016-03-06 00:14:02

标签: javascript ember.js

我有一个只提供数据作为数组的服务:

// services/countries.js
import Ember from 'ember';

export default Ember.Service.extend({

   countries: [
   {
      "name": "Afghanistan",
      "code": "AF"
   },
   ....
   ]
});

我可以在帮助中成功访问:

// helpers/countries.js
export default Ember.Helper.extend({
    countries: Ember.inject.service('countries'),
    compute(params, hash) {
        console.log(this.get('countries.countries'));
        return 'test';
    }
});

现在我在该服务中添加了一个功能来搜索给定的国家/地区代码并返回匹配的国家/地区:

// in services/countries.js
...
getByCode: function(code) {
    this.get('countries').forEach(function(item) {
        if(item.code===code) {   // finds the right item
            console.log('returning item:');
            console.log(item);   // outputs the right object
            return item;         // I expected to have the same item retured..
        }
    });
return {name:'not found', code: ''};
},
...

当我在帮助者中调用该功能时

// in helpers/countries.js
...
compute(params, hash) {
   let country = this.get('countries').getByCode('DE');
   console.log(country); // outputs {name: 'not found',..} instead of the found and returned(?) item
   return country.name;
}
...
请注意,正确的输出(服务中的console.log)是错误的'输出:

// console output
returning item:   roles.js:6 
Object {name: "Germany", code: "DE", nameLocal: "Deutschland"}   hash.js:2
Object {name: "not found", code: ""}

让我感到好奇的是,在控制台中,错误的是'提到了.js(roles.js - 这是另一个没有此功能的服务)

所以我的问题是为什么我会返回/输出不同的项目?

为了完整性: 我只在我的模板中使用这个助手一次:

{{#if model.country}}{{countries model.country}}{{/if}}

(当然也会输出错误的国家/地区)

Ember-CLI 1.13.7 Ember 2.0.1

1 个答案:

答案 0 :(得分:1)

return循环中的forEach存在问题。

  

除了by之外,没有办法停止或中断forEach()循环   抛出一个例外。如果需要这样的行为,请使用forEach()方法   是错误的工具。

如果您想使用forEach,请将您的功能修改为:

getByCode: function(code) {
    var found = null;
    this.get('countries').forEach(function(item) {
        if(item.code === code) {
            found = item;
        }
    });
    return found != null ? found : {name:'not found', code: ''};
},

此处有更多信息:EmberJS: is it possible to break from forEach?

但是,我建议改用:

getByCode: function(code) {
   let country = this.get('countries').find(c => c.code === code);
   return country != undefined ? country : {name:'not found', code: ''};
}