Angular 2自定义服务未注入指令

时间:2016-03-04 21:45:40

标签: angular angular2-directives angular2-di

我有这样的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实例,这是不可取的。

有什么想法吗?或者是设计?

2 个答案:

答案 0 :(得分:2)

这可能是导入顺序的问题...如果您在app.component.ts之前导入ChartDirective,则可能会出现错误:

  

没有ChartDataService的提供商! (ChartDirective - &gt; ChartDataService)

在导入组件本身之前,您应该导入子组件/指令使用的服务:

ChartDataService

我无法在此处重现此问题:http://plnkr.co/edit/NoZJnCMlqKkOMm5erfDW,但我可以确认它可能会发生:

// no error
import {ChartDataService} from '../service/chartData.service'
import {ChartDirective} from '../chart.directive'

// can cause an error
import {ChartDirective} from '../chart.directive'
import {ChartDataService} from '../service/chartData.service'

Error No Error

答案 1 :(得分:0)

我忘了提到我正在使用beta.7。更新到beta.8后问题消失了。

相关问题