Sar*_*dav 9 dependency-injection injectable typescript angular
我不明白何时使用@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;
}
}
Run Code Online (Sandbox Code Playgroud)
和..
import {Injectable} from '@angular/core';
import {Bun} from './bun';
@Injectable()
export class Hamburger {
constructor(public bun: Bun) {
}
}
Run Code Online (Sandbox Code Playgroud)
该@Injectable
装饰的目的是实际设置哪些依赖关系注入到相关类的构造一些元数据.它是一个不需要参数的类装饰器.如果没有这个装饰器,就不会注入依赖...
@Injectable()
export class SomeService {
constructor(private http:Http) {
}
}
Run Code Online (Sandbox Code Playgroud)
所述@Inject
装饰必须在构造参数的级别被用于指定关于元素注入元数据.没有它,使用参数类型(obj:SomeType
相当于@Inject(SomeType) obj
).
@Injectable()
export class SomeService {
constructor(@Inject(Http) private http:Http, @Inject('sometoken') obj) {
}
}
Run Code Online (Sandbox Code Playgroud)
是一种让 Angular 知道必须注入参数的手动机制。
使用 TypeScript 时,@Inject 仅用于注入原语。例如:
export class AppComponent {
encryption = this.chatWidget.chatSocket.encryption;
constructor(@Inject(ChatWidget) private chatWidget) { }
}
Run Code Online (Sandbox Code Playgroud)
让 Angular 知道一个类可以与依赖注入器一起使用。
例如:
@Injectable()
export class ChatWidget {
constructor(
public authService: AuthService,
public authWidget: AuthWidget,
public chatSocket: ChatSocket) { }
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,Angular 的注入器通过使用类型信息来确定将什么注入到 ChatWidget 的构造函数中
归档时间: |
|
查看次数: |
6787 次 |
最近记录: |