I have app.component like this.
import {Component} from "angular2/core"
import {HTTP_PROVIDERS} from "angular2/http"
import {ChartDataService} from '../service/chartData.service'
import {FilterService} from "../service/filter.service"
@Component({
selector: 'app',
template: `
<sidebar (filterChange)="onFilterChange($event)"></sidebar>
<div dsChart></div>
`,
directives: [SidebarComponent, ChartDirective],
providers: [HTTP_PROVIDERS, FilterService, ChartDataService],
styleUrls: ['app/main/app.component.css']
})
export class AppComponent {
//some more code
}
chartData.service.ts:
import {Injectable} from 'angular2/core'
import {Http, Response, Headers, RequestOptions, RequestMethod} from 'angular2/http'
import {Url} from '../url'
import {FilterModel} from '../model/filter.model'
import {INode} from "../model/node.model"
@Injectable()
export class ChartDataService {
constructor(private _http: Http) {
this._headers.append('Content-Type', 'application/json');
}
getData(model?: FilterModel) {
}
}
Then I try to use ChartDataService inside chart.directive, which is a child component to app.component. chart.directive.ts:
import {Directive, ElementRef, Input, OnInit} from 'angular2/core'
import {ChartDataService} from "../service/chartdata.service"
@Directive({
selector: '[dsChart]'
})
export class ChartDirective implements OnInit {
constructor(
private el: ElementRef,
private _dataService: ChartDataService) {
}
ngOnInit() {
this._dataService.getData()
.then(node => this._render(node))
.catch(error => { throw error });
}
private _render(root: INode) {}
}
But it fails with Via the docs each component has an injector which creates dependencies at a component level scope. If there are no any appropriate component level providers parent component's provider is used. This works fine for classes with @Component()
decorator. Adding providers: [ChartDataService]
to @Directive
declaration helps, but that means each decorator will have separate instance of ChartDataService
which is undesiarable.
Any ideas? Or is it by design?