【问题标题】:What is the difference between @Inject and @Injectable in Angular 2 typescriptAngular 2打字稿中@Inject和@Injectable有什么区别
【发布时间】:2016-09-15 20:48:45
【问题描述】:

我不明白什么时候使用@Inject,什么时候使用@Injectable?

  import {Component, Inject, provide} from '@angular/core';
    import {Hamburger} from '../services/hamburger'; 
    export class App {
       bunType: string;
       constructor(@Inject(Hamburger) h) {
         this.bunType = h.bun.type;
       }
     }

还有..

  import {Injectable} from '@angular/core';
    import {Bun} from './bun';
    @Injectable()
    export class Hamburger {
      constructor(public bun: Bun) {
      }
    }

【问题讨论】:

    标签: dependency-injection typescript angular injectable


    【解决方案1】:

    您必须阅读此区别-@Inject and @Injectable

    @Inject()

    是一种手动机制,用于让 Angular 知道必须注入参数。

    使用 TypeScript 时,@Inject 仅用于注入原语。 例如:

    export class AppComponent {
      encryption = this.chatWidget.chatSocket.encryption;
    
      constructor(@Inject(ChatWidget) private chatWidget) { }
    }
    

    @Injectable()

    让 Angular 知道一个类可以与依赖项一起使用 注射器。

    例如:

    @Injectable()
    export class ChatWidget {
    constructor(
        public authService: AuthService,
        public authWidget: AuthWidget,
        public chatSocket: ChatSocket) { }
    }
    

    在上面的例子中,Angular 的注入器通过使用类型信息来确定将什么注入到 ChatWidget 的构造函数中

    【讨论】:

      【解决方案2】:

      @Injectable 装饰器旨在实际设置一些关于将哪些依赖项注入关联类的构造函数的元数据。这是一个不需要参数的类装饰器。如果没有这个装饰器,就不会注入依赖...

      @Injectable()
      export class SomeService {
        constructor(private http:Http) {
        }
      }
      

      @Inject 装饰器必须在构造函数参数级别使用,以指定有关要注入的元素的元数据。没有它,使用参数的类型(obj:SomeType 相当于@Inject(SomeType) obj)。

      @Injectable()
      export class SomeService {
        constructor(@Inject(Http) private http:Http, @Inject('sometoken') obj) {
        }
      }
      

      【讨论】:

      • 谢谢@Thierry,但你能解释一下为什么我们使用@Injectable() 我们可以直接导出类然后我们为什么使用@Injectable()?
      • 如果您可以不使用 @Injectable 装饰器来导出类。除非您想在其中注入一些东西,否则它将起作用...没有装饰器,将不会在导出类的相应实例中注入任何内容。
      • 如果我要导出一个类并将其导入某个模块并在代码构造函数(示例:示例)中使用它,我已经对此进行了测试。那么在该课程之前使用@Injectable()是否有任何理由
      • @ThierryTemplier 你能回答这个问题吗? stackoverflow.com/questions/65336962/…
      猜你喜欢
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-25
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多