I have a simple service in Angular
// service.ts
export class SimpleService {
// ...
}
// component.ts
@Component({
selector: 'my-component',
templateUrl: 'components/mycomp/mycomp.html',
providers: [
SimpleService
]
})
class MyComponent {
constructor(private ss: SimpleService) {}
}
This above code never works. I get an error: Uncaught Error: Can't resolve all parameters for MyComponent: (?).
However, if I change my constructor definition to:
class MyComponent {
constructor(@Inject(SimpleService) private ss: SimpleService) {}
}
Then it works. Even documentation doesn't seem to use @Inject
. From the documentation I understand that @Inject
is explicitly required when my provider token is not class; like, trying to inject primitive values, or using opaque tokens, etc.
Also, I am confused in regards to typescript. Official documentation clearly mentions that when @Inject()
is not present, Injector will use the type annotation of the parameter. If type information is erased during typescript transpilation and DI is happening when app is running, how can Angular use type annotation at runtime? Is there anything I am missing?