I am working on an Angular2 component that requires the injection of a service called KeyValueService
in its constructor. This service is used to patch the new router's missing data
on routes.
KeyValueService
import {Injectable} from '@angular/core';
@Injectable()
export class KeyValueService {
private KeyValues: Array<KeyValue>;
constructor() { }
Set(key, value) {
...
}
Get(key): any {
...
}
}
export class KeyValue {
Key;
Value;
constructor(key, value) {
this.Key = key;
this.Value = value;
}
}
Root component
import {Component} from '@angular/core';
import {Child} from './Child';
@Routes([
{ path: '/Child', component: Child}
])
@Component({
providers: [
ROUTER_PROVIDERS
],
directives: [ROUTER_DIRECTIVES],
selector: 'Root',
template:
'<div>
<router-outlet></router-outlet>
<a [routerLink]="['/Child']">Child</a>
</div>'
})
export class Root {
}
Child
import {Component} from '@angular/core';
import {KeyValueService} from './KeyValueService';
@Component({
providers: [KeyValueService],
selector: 'Child',
template:
'<div>
Child!!
</div>'
})
export class Child {
constructor(keyValue: KeyValueService) {
}
}
I have encountered an error stating that there are no providers for keyValueService
. Strangely, when I define the KeyValueService
provider at the root component level, it works as expected. However, when I try to define the provider where it is actually needed (in the Child
component), it fails to work. Can anyone explain why this is happening, considering I have already defined KeyValueService
as a provider for the Child
component?