如何处理Angular2中嵌套组件的依赖关系?

时间:2016-03-15 04:03:49

标签: javascript typescript angular

我遇到了这个错误:

$numrows >= 1

以下是细分:

我有服务

browser_adapter.js:76 Error: Cannot resolve all parameters for NestedComponent(undefined). Make sure they all have valid type or annotations.
    at NoAnnotationError.BaseException [as constructor] 

这可以注入组件,像这样,没有问题:

@Injectable()
export class MyService {
    doSomething() {
        console.log("This is a service, and it's doing stuff");
    }
}

但是,当我尝试将服务注入嵌套组件时,我遇到了问题:

@Component({
    selector: 'parent-component',
    template: '<p>This works great!</p>',
    providers: [MyService]
})
export class ParentComponent {
    constructor(private _myService: MyService) {}

    ngOnInit() {
        this._myService.doSomething();
    }
}

当我尝试将嵌套组件插入父组件时,我得到错误^。我怎样才能做到这一点。

@Component({
    selector: 'nested-component',
    template: "<p>This doesn't work. :(</p>",
    providers: [MyService]
})
export class NestedComponent {
    constructor(private _myService: MyService) {}

    ngOnInit() {
        this._myService.doSomething();
    }
}

对于它的价值,即使我在我的app的bootstrap函数中包含MyService,我仍会遇到该错误:

@Component({
    selector: 'parent-component',
    template: '<nested-component></nested-component>',
    directives: [NestedComponent]
})
export class ParentComponent {
}

1 个答案:

答案 0 :(得分:2)

如果您想共享单个服务实例, 不要使用

providers: [MyService]

在每个组件中。

请看这个不使用providers:[...]shared instance, not providers used, registered into bootstrap

的例子

如果你不想分享, 删除

providers: [MyService]

来自嵌套组件。

请看这个使用providers:[...]not shared instance, not registered into bootstrap, used with providers in parent only and not in child,

的示例