您如何处理 Angular2 中嵌套组件的依赖关系
How are do you handle dependencies for nested components in Angular2?
我遇到了这个错误:
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 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
、
相关文章:
- 在嵌套组件中使用 react 组件时模块中断
- 在 React 中嵌套组件,props 不会传递给子组件
- 反应:在嵌套组件上冒泡点击事件
- Angular 1.5 嵌套组件绑定父值
- 在 knockoutjs 中嵌套组件
- 您如何处理 Angular2 中嵌套组件的依赖关系
- 如何处理 React 嵌套组件循环依赖?(使用 es6 类)
- AngularJS通过嵌套组件向上传播更改
- 如何在 RivetsJS 中处理递归嵌套组件
- 了解嵌套组件绑定在 KnockoutJS 上的工作原理
- 聚合物.js嵌套组件中的数据绑定
- 如何以正确的方式嵌套组件
- 映射到嵌套组件的 Elm 效果
- Material-ui:如何在嵌套组件中停止单击事件的传播
- 使用键来识别 React.js 中的嵌套组件
- Angular2 嵌套组件: 错误: core_2.输入不是函数 加载 http://localhost:9080/ap
- 如何将全局状态数据处理到Redux中的深度嵌套组件中
- React dnd-不确定如何为相同类型的嵌套组件启用拖放
- React Router-在嵌套组件中安装组件
- Uikit.可嵌套组件-如何从移动的项目获取id