I have a working angular2 Componen
t.
I implemented a class for some service (using ng.core.Class
if that matters).
What are the minimal steps to inject my service to my Component
? Should I include my service in bootstrap function? Should I use any of ng.core.Inject
or ng.core.Injectable?
All my experiments failed so far.
Asked
Active
Viewed 1,577 times
5

twernt
- 20,271
- 5
- 32
- 41

Sergey P. aka azure
- 3,993
- 1
- 29
- 23
-
I refer to current beta version of angular2 in this question. – Sergey P. aka azure Dec 30 '15 at 15:16
1 Answers
12
You can do it super simple. Just create a class an pass it through providers
property or through bootstrap
For example
// Alternative 1
var Service = ng.core.Class({
constructor : function() {},
someFunction : function() {
console.log('Some function');
}
})
// Alternative 2
var Service = function() {}
Service.prototype.someFunction = function() {
console.log('Some function');
}
Then pass it to the component
var Component = ng.core.
Component({
selector: 'cmp',
template : '',
providers : [Service]
}).
Class({
constructor: [Service, function(svc) {
svc.someFunction();
}]
});
Or through bootstrap
ng.platform.browser.bootstrap(Component, [Service]);
Here's an example so you can take a look at it.
Reference
- Class (you can find some examples of its usage in the comments)

Eric Martinez
- 31,277
- 9
- 92
- 91
-
Thanks. It works that way. The reason it *not* worked for me is that I was trying to refer to `Service` before I created it. So the order of js files loading is important with such approach. – Sergey P. aka azure Dec 31 '15 at 10:54
-
@SergeyP.akaazure can you please accept the answer if it answers your question? – Günter Zöchbauer Jan 04 '16 at 19:55
-
what if i need to use two services?? how can i specify that in constructor? – Midhun Mohan Apr 01 '17 at 14:31