1

It drives me crazy. I have a really simple "problem" and it took me hours and still have no idea whats going on.

I have a child service which inherits from a parent service (I'm using ES6). The constructor takes an 1 argument called options. options will be assigned to this._defaults.

Now before I pass the options into my object (new Service(options)) I populate options with some data. To keep it simple, my current options object looks like this:

const options = {
  types: []
}

Now I add some stuff into the types array, like this:

const Types = {
  standard: {
    some: 'data'
  },
  freeroll: {
    some: 'data'
  },
  mainevent: {
    some: 'data'
  },
  qualifier: {
    some: 'data'
  }
};

angular.forEach(Types, (val, key) => {
  options.types[key] = true;
});

I assign my service to the scope like this:

$scope.service = new Service(options)

and output the service using console. The console now says the value of _defaults.types is Array(0). When I click on the array the correct values will be shown but the scope is not aware of that.

How is that? Doesn't Array(0) mean that at the time of the console.log() the array wasn't filled with any values but has been later? Like an async function would do?

Here is a plunk of my problem.

1 Answer 1

2

The problem is that types is an array and you're treating it like a plain Object. You can solve this one of two ways.

First just change types to an Object:

const options = {
  types: {}
};

Or, if you need an Array, change how you're adding items to the array:

angular.forEach(Types, (val, key) => {
  options.types.push({
      type: key,
      value: val
  });
});

Note that this is just one way of turning the object into an array, the data structure you end up with is up to you.

Sign up to request clarification or add additional context in comments.

3 Comments

That's true. It should be mentioned that it's just how JSON.stringify works, which is used by json filter internally.
Well what should I say. It's such an easy mistake and I didn't see it. Totally makes sense, thank you.
no problem--when you look at code too long (especially you're own) it's hard to see the little killers like brackets vs braces

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.