samedi 5 mars 2016

function in service not returning right values

I have a service that simply provides data as an array:

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

export default Ember.Service.extend({

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

which I can successfully access in a helper:

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

Now I added a function to that service to search for a given country-code and to return the matching country:

// 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: ''};
},
...

When I call that function in my helper

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

note, that the correct output (console.log in service) is BEFORE the 'wrong' output:

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

What also makes me curious is, that in the console the 'wrong' .js is mentioned (roles.js - which is another service, that does not have this function)

So my question is why do I get a different item returned/output?

For completeness: I user this helper in my template only once like so:

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

(which of course also outputs the 'wrong' country)

Ember-CLI 1.13.7 Ember 2.0.1




Aucun commentaire:

Enregistrer un commentaire