Angular 2打字稿中@Inject和@Injectable有什么区别 [英] What is the difference between @Inject and @Injectable in Angular 2 typescript

查看:422
本文介绍了Angular 2打字稿中@Inject和@Injectable有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白何时使用@Inject和何时使用@Injectable?

I don't understand When to use @Inject and when to use @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) {
      }
    }

推荐答案

@Injectable装饰器的目的是实际设置一些元数据,这些元数据将哪些依赖项注入到相关类的构造函数中.这是一个不需要参数的类装饰器.没有这个装饰器,将不会注入依赖项...

The @Injectable decorator aims to actually set some metadata about which dependencies to inject into the constructor of the associated class. It's a class decorator that doesn't require parameters. Without this decorator no dependency will be injected...

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

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

The @Inject decorator must be used at the level of constructor parameters to specify metadata regarding elements to inject. Without it, the type of parameters is used (obj:SomeType is equivalent to @Inject(SomeType) obj).

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

这篇关于Angular 2打字稿中@Inject和@Injectable有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆