I know how to inject a service into a component (via @Component), but how can I use DI to pass around services outside of components?
In other words, I don\'t want t
not sure if an answer is still required so i would go ahead and try to answer this.
Consider the following example where we have a Component which uses a service to populate some values in its template like below
testComponent.component.ts
import { Component } from "@angular/core"
import { DataService } from "./data.service"
@Component({
selector:"test-component",
template:`
- {{ person.name }}
})
export class TestComponent {
persons:;
constructor(private _dataService:DataService){
this.persons = this._dataService.getPersons()
}
}
The above code is pretty simple and it will try to fetch whatever getPersons return from the DataService. The DataService file is available below.
data.service.ts
export class DataService {
persons:;
constructor(){
this.persons = [
{name: "Apoorv"},
{name: "Bryce"},
{name: "Steve"}
]
}
getPersons(){
return this.persons
}
The above piece of code will work perfectly fine without the use of the @Injectable decorator. But the problem will start when our service(DataService in this case) requires some dependencies like for eg. Http. if we change our data.service.ts
file as below we will get an error saying Cannot resolve all parameters for DataService(?). Make sure they all have valid type or annotations.
import { Http } from '@angular/http';
export class DataService {
persons:;
constructor(){
this.persons = [
{name: "Apoorv"},
{name: "Bryce"},
{name: "Steve"}
]
}
getPersons(){
return this.persons
}
This has something to do with the way decorators function in Angular 2. Please read https://blog.thoughtram.io/angular/2015/05/03/the-difference-between-annotations-and-decorators.html to get an in depth understanding of this issue.
The above code will also not work as we have to import HTTP in our bootstrap module as well.
But a thumb rule i can suggest is that if your service file needs a dependency then you should decorate that class with a decorator @Injectable.
reference:https://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html