依赖注入 – Angular 2打字稿中@Inject和@Injectable之间的区别是什么
发布时间:2020-05-23 11:13:38 所属栏目:程序设计 来源:互联网
导读:我不明白何时使用@Inject以及何时使用@Injectable? import {Component, Inject, provide} from @angular/core; import {Hamburger} from ../services/hamburger; export class App { bunType: string;
|
我不明白何时使用@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) {
}
}
@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) {
}
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
