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

How are do you handle dependencies for nested components in Angular2?

本文关键字:嵌套 组件 关系 依赖 Angular2 何处理 处理      更新时间:2023-09-26

我遇到了这个错误:

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();
    }
}

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

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

对于它的价值,即使我将MyService包含在应用程序的引导函数中,我仍然会遇到该错误:

function main() {
  return bootstrap(App, [
    // These are dependencies of our App
    HTTP_PROVIDERS,
    ROUTER_PROVIDERS,
    MyService,
    ELEMENT_PROBE_PROVIDERS // remove in production
  ])
  .catch(err => console.error(err));
}
document.addEventListener('DOMContentLoaded', main);
如果要

共享单个服务实例,不要使用

providers: [MyService]

在每个组件中。

看看这个不使用providers:[...]
shared instancenot providers usedregistered into bootstrap的例子

如果你不想分享,删除

providers: [MyService]

从嵌套组件。

看看这个例子,它使用了providers:[...]
not shared instancenot registered into bootstrapused with providers in parent only and not in child