garrettmac
garrettmac

Reputation: 8585

Angular2 Dependency Injection: What's the "..." syntax I see before some injected package's name (ie 'providers = [...SomeProvider]')

I'm just getting started in Angular2 and normally injecting providers looks like:

providers : [SomeProvider],

However I have been seeing some packages that include a "..." before the provider name that is being injected like:

providers : [...SomeProvider],

Why is this being done? What is the ... and what is it doing?

Upvotes: 1

Views: 37

Answers (1)

Ricardo Varanda
Ricardo Varanda

Reputation: 147

That is the spread operator. The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.

You might be thinking why we need this?

A better apply

Example: it is common to use Function.prototype.apply in cases where you want to use an array as arguments to a function.

function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction.apply(null, args);

With ES6 spread you can now write the above as:

function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args);

Any argument in the argument list can use the spread syntax and it can be used multiple times.

function myFunction(v, w, x, y, z) { }
var args = [0, 1];
myFunction(-1, ...args, 2, ...[3]);

More information and examples can be found on it here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator

Upvotes: 2

Related Questions