【发布时间】:2016-03-17 12:40:10
【问题描述】:
角度:2.0.0-beta.9
是否可以将非 @Injectable 类注入到 component 中?例如,此类可能来自第三方库。
【问题讨论】:
标签: typescript angular
角度:2.0.0-beta.9
是否可以将非 @Injectable 类注入到 component 中?例如,此类可能来自第三方库。
【问题讨论】:
标签: typescript angular
是的,这是可能的。事实上,@Injectable 装饰器并不是要指定一个类可以注入到其他类中,而是要在其构造函数级别向其中注入一些东西。
如果您不想在类中注入某些内容,则不必添加 @Injectable 装饰器。这个类可以注入到其他类中。
我认为这个 Github 问题可以帮助你:
这里重要的是理解装饰器和注释之间的区别。这是一篇关于这个主题的精彩文章:
【讨论】:
我认为是的,这是可能的。我已经在没有 @Injectable 装饰器的情况下对其进行了测试,并且效果很好。
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";
}
}
如果你想知道,因为某些类,在构造函数中使用 DI 而不要使用@Injectable()。因为这个修饰了@,例如@Components。
HeroesComponent 也有一个注入依赖。我们为什么不添加 @Injectable() 到 HeroesComponent?
如果我们真的想要,我们可以添加它。没有必要,因为 HeroesComponent 已经用@Component 装饰了。打字稿 为任何带有装饰器的类和任何装饰器生成元数据 会的。
有关更多信息,您可以阅读此link Angular page
【讨论】:
如果类有依赖关系,你仍然可以在 DI 中使用它。只需为它提供一个工厂
如果您希望能够注入一个本身具有依赖项(构造函数参数)但不想或不能应用 @Injectable() 的类,那么您可以改用工厂
bootstrap(AppComponent, [
SomeDep,
provide(SomeType, {useFactory: (dep) => new SomeType(dep),
deps: [SomeDep]})
]);
您可以为此类提供程序创建变量,使其易于重复使用,而无需这种繁琐的声明(例如 HTTP_PROVIDERS)
export const SOME_TYPE_PROVIDERS: any[] = [
SomeDep,
provide(SomeType, {useFactory: (dep) => new SomeType(dep),
deps: [SomeDep]})
];
然后像这样使用它
bootstrap(AppComponent, [SOME_TYPE_PROVIDERS]);
【讨论】: