我有这样的 app.component 。
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) {
}
}
然后我尝试在chart.directive 中使用ChartDataService,它是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) {}
}
但是它通过文档失败了,每个组件都有一个注入器,它在组件级别范围内创建依赖项。如果没有任何适当的组件级提供程序,则使用父组件的提供程序。这适用于带有@Component()
装饰器的类。添加providers: [ChartDataService]
到@Directive
声明会有所帮助,但这意味着每个装饰器都会有单独的实例,ChartDataService
这是不受欢迎的。
有任何想法吗?还是设计使然?