@Injectable
的意思是
"allow injection of whatever into the class which the decorator is above"
或者
Does it mean "allow me to inject this class (which the decorator is above) into 'wherever' in the application"?
最佳答案
@Injectable
只是一个标记,告诉 Angular 引擎该类可以由注入(inject)器创建。在运行时, Angular 告诉注入(inject)器读取所有@Injectable
类并实例化它们,并使它们可注入(inject)到引用它们的类中。
例如,假设 Angular 中有一个名为 UserService
的服务,并且您需要在名为 RegistrationComponent
的组件中使用该服务。
@Injectable()
export class UserService {
saverUser(User user)
.....
}
然后在RegistrationComponent
构造函数中声明一个引用UserService
的输入参数,它告诉Angular应将UserService注入(inject)到RegistrationComponent
,当然,之前 @Injectable
标记应该在 UserService
RegistrationComponent.ts
export class RegistrationComponent
constructor(private userService: UserService) { }
在 Spring 上下文中,@Component
与 @Injectable
起着类似的作用,当然它们在实现上有很多差异,但两者的作用相似 Angular 色。 @Component
是一个注释,它告诉 Spring 某些特定的类必须被视为自动检测的候选类,并且该类可以存在于 Spring 容器中。 Spring容器中的组件(bean)可以注入(inject)到其他类中。
@Autowired
与 @Component
不同。 @Autowired
表示特定的类成员应该由 Spring DI 容器提供或注入(inject)。
有关更多信息,请参阅以下链接:
关于javascript - @Injectable 装饰器基本上相当于 Spring 中的 @Component 或 @Autowired 的 Angular 2 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45665801/