javascript - @Injectable 装饰器基本上相当于 Spring 中的 @Component 或 @Autowired 的 Angular 2 吗?

标签 javascript angularjs spring frontend angular-fullstack

@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)。

有关更多信息,请参阅以下链接:

Angular Dependency Injection

@Autowired Spring Documentation

@Component Spring Documentation

关于javascript - @Injectable 装饰器基本上相当于 Spring 中的 @Component 或 @Autowired 的 Angular 2 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45665801/

相关文章:

javascript - 自定义 ESLint 规则中的异步代码

javascript - 获取页面加载的详细信息,并在 Controller 中共享

java - ConversionServiceFactoryBean 不起作用

java - setCharacterStream 引起的 AbstractMethodError

javascript - addEventListener 类型 'click' 实际上表现得像 'load'

javascript - 补间对象的碰撞检测

javascript - 用户配置文件栏的更好方法

angularjs - 用户界面网格 : directive as cellTemplate

angularjs - 如何使用提供者而不是函数来装饰 $log 服务

使用 Maven 打包 JAR 和 WAR 的 Spring Boot 迁移问题