angular: 2.0.0-beta.9
Is it possible to inject a non @Injectable
class into a component
? For example, this class could come from a Third party library.
angular: 2.0.0-beta.9
Is it possible to inject a non @Injectable
class into a component
? For example, this class could come from a Third party library.
Yes, it's possible. In fact the @Injectable
decorator isn't to specify that a class is injectable into other ones but that you want to inject something in it at the level of its constructor.
If you don't want to inject something in your class, it's not mandatory to add the @Injectable
decorator. This class can be injected into other ones.
I think that this Github issue could help you:
What is important here is to understand the difference between decorators and annotations. Here is a great article on this subject:
I think yes it is possible. I have tested it without @Injectable
decorator and it works fine.
AuthService.ts
import {Injectable} from 'angular2/core';
import {Http, Response,HTTP_PROVIDERS} from 'angular2/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';
export interface sharedObject{
firstName:string;
lastName:stirng;
}
export class AuthService{
user:sharedObject;
constructor()
{
console.log('AuthService started')
this.user={firstName:"micronyks",lastName:"shah"};
}
change() {
console.log('change to angular2');
this.user.firstName="micronyks1";
this.user.lastName="shah1";
}
}
If you wonder, because some class, use DI in the constructor and do not use @Injectable()
. Because this decorated @, for example @Components
.
The HeroesComponent has an injected dependency too. Why don't we add @Injectable() to the HeroesComponent?
We can add it if we really want to. It isn't necessary because the HeroesComponent is already decorated with @Component. TypeScript generates metadata for any class with a decorator, and any decorator will do.
For more info you can read this link Angular page
If the class has dependencies you still can use it in DI. Just provide a factory for it
If you want to be able to inject a class that itself has dependencies (constructor arguments) but don't want or can't apply @Injectable()
, then you can use a factory instead
bootstrap(AppComponent, [
SomeDep,
provide(SomeType, {useFactory: (dep) => new SomeType(dep),
deps: [SomeDep]})
]);
You can create variables for such providers to make them easily reusable without this cumbersome declaration (like for example HTTP_PROVIDERS
)
export const SOME_TYPE_PROVIDERS: any[] = [
SomeDep,
provide(SomeType, {useFactory: (dep) => new SomeType(dep),
deps: [SomeDep]})
];
and then use it like
bootstrap(AppComponent, [SOME_TYPE_PROVIDERS]);