【发布时间】:2016-03-04 21:45:39
【问题描述】:
我有这样的 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 实例,这是不可取的。
有什么想法吗?还是设计使然?
【问题讨论】:
标签: angular angular2-directives angular2-di