【问题标题】:function in service not returning right values服务中的函数未返回正确的值
【发布时间】:2016-03-06 00:14:01
【问题描述】:

我有一个服务,它只是以数组的形式提供数据:

// 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

【问题讨论】:

    标签: javascript ember.js


    【解决方案1】:

    returnforEach 循环中存在问题。

    没有办法停止或中断 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: ''};
    }
    

    【讨论】:

    • 看起来很有希望!我会测试它然后接受!非常感谢!
    • 经过测试,效果很好!谢谢!我不知道不能像普通的 for 循环那样打破 forEach ......(我使用了你的第二个版本)
    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多