2

我有这样的 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这是不受欢迎的。

有任何想法吗?还是设计使然?

4

2 回答 2

2

这可能是导入顺序的问题...如果在app.component.ts导入ChartDirective之前ChartDataService您可能会收到您提到的错误:

ChartDataService 没有提供者!(ChartDirective -> ChartDataService)

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

// 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'

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

// routes.ts
// no error
export {SettingsRoute} from './routes/settings/settings.route'
export {RootRoute} from './routes/root/root.route'

// this causes error
// export {RootRoute} from './routes/root/root.route'
// export {SettingsRoute} from './routes/settings/settings.route'

// root.route.ts
import {SettingsRoute} from './routes'
@RouteConfig([
  { path: '/settings/...', name: 'Settings', component: SettingsRoute },
])
export class RootRoute {...}

错误 没有错误

于 2016-03-05T02:03:32.963 回答
0

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

于 2016-03-04T23:09:26.463 回答