2016-03-06 130 views
2

我有簡單地提供數據作爲陣列的服務:功能沒有返回正確的值

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

(這當然也輸出了 '錯誤' 的國家)

灰燼,CLI 1.13 .0 Ember 2.0.1

回答

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: ''}; 
} 
+0

看起來很有希望!我會測試它,然後接受!非常感謝! – Jeff

+0

測試過,工作像魅力!謝謝!我不知道無法像循環中的普通循環那樣打破forEach ...(我使用了第二個版本) – Jeff