Reputation: 6027
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]
I have a service
@Injectable()
export class MyService {
doSomething() {
console.log("This is a service, and it's doing stuff");
}
}
That can be injected into components, like this, without issue:
@Component({
selector: 'parent-component',
template: '<p>This works great!</p>',
providers: [MyService]
})
export class ParentComponent {
constructor(private _myService: MyService) {}
ngOnInit() {
this._myService.doSomething();
}
}
I have problems, however, when I try to inject the service into nested components, like this:
@Component({
selector: 'nested-component',
template: "<p>This doesn't work. :(</p>",
providers: [MyService]
})
export class NestedComponent {
constructor(private _myService: MyService) {}
ngOnInit() {
this._myService.doSomething();
}
}
When I try to plug the nested component into the parent component, I get the error up there ^. How can I achieve this.
@Component({
selector: 'parent-component',
template: '<nested-component></nested-component>',
directives: [NestedComponent]
})
export class ParentComponent {
}
For what it's worth, I still run into that error, even when I include MyService in the bootstrap function of my app:
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);
Upvotes: 0
Views: 118
Reputation: 55443
If you want to share single instance of service, dont use,
providers: [MyService]
in each component.
Look into this example which doesn't use providers:[...]
,shared instance
, not providers used
, registered into bootstrap
And if you don't want to share, remove ,
providers: [MyService]
from nested-component.
Look into this example which uses providers:[...]
,not shared instance
, not registered into bootstrap
, used with providers in parent only and not in child
,
Upvotes: 2