我有app.component這樣。角2定製服務沒有注入到指令
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) {
}
}
然後我嘗試使用ChartDataService內chart.directive,這是一個子組件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
的單獨實例。
任何想法?或者是由設計?
好,因爲我不知道爲什麼它不適合你。 –