Angular 2 - Injectable() 装饰器

标签 angular dependency-injection angular2-services

我不完全理解 Angular 2 中的 @Injectable 装饰器。即使我不使用它,服务也可以工作。 (看下面的例子)

使用@Injectable装饰器的目的是什么?

下面是两个示例,一个带有 Injectable ,一个没有 Injectable 以及相应的 plunker 示例:

与@Injectable Example1 `

@Injectable()
export class AppService{
  get():any[]{
    return "something"
}

没有@Injectable Example2

export class AppService{
  get():any[]{
    return "something"
}

我当然知道使用 @Injectable 装饰器进行依赖注入(inject)的原因,但就像我之前说的,我不完全理解。有人可以解释一下吗?

最佳答案

如果服务没有构造函数参数,则不需要可注入(inject)。无论如何,我们都会考虑将其添加到所有服务中,因为这是一个常见的错误,后来添加了参数,但 @Injectable() 装饰器因为之前在工作而被忘记了。

关于Angular 2 - Injectable() 装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41804301/

相关文章:

android - 我如何在 ionic 2 中打开应用程序短信 Composer View

asp.net-mvc - Post 方法在 Asp.net 核心 Web API Controller 中返回 404

javascript - 过滤器不是自定义管道 Angular 2 中的函数

angular - 在 Angular2 中访问子组件的提供者

angular - 如何在 Angular 2 应用程序中配置不同的开发环境

html - 在 ngFor Angular 2 中设置输入类型复选框的选中状态

javascript - 在 Angular 7 中测试 PhantomJS Array.prototype.includes()

c# - 如何将具体类注册到通用接口(interface)?

c# - 如果一个类需要在方法中需要时创建另一个类的多个实例,则进行依赖注入(inject)

android - Roboguice 和模拟 : How to have roboguice inject a mock service when testing but use the REAL otherwise?