使用Injection Token将字符串类型的参数注入到类的构造函数里
一個常見的錯誤消息:
error NG2003 - No suitable injection token for parameter
構造函數里有個參數類型為string:
constructor(@Inject('apiUrl') private myname) {console.log('Jerry inject: ' + myname);}這個myname通過注解@Inject修飾,id為apiUrl.
誰負責注入apiUrl呢?在app module里:
providers: [{ provide: JerrySandBoxService },{ provide: GreetingService, useClass: EnglishGreetingService},{provide: 'apiUrl',useValue: 'http://localhost:4200/heros'}],運行時:
另一個例子:
const MY_SERVICE_TOKEN = new InjectionToken<MyService>('Manually constructed MyService', {providedIn: 'root',factory: () => {console.log('MyService factory called');return new MyService();} });構造函數:
constructor(private injectorJerry: Injector, private hostComponentService: HostComponentService, @Inject(TOKEN_HOST_CLASS_PROVIDER) h) {console.log('in HostDecoratorComponent, Host component service got from own Injector: ',hostComponentService, ' HostTokenComponentService: ', h);h.print();const BASE_URL = new InjectionToken<string>('只是描述');const injector =Injector.create({providers: [{provide: BASE_URL, useValue: 'http://localhost'}]});const url = injector.get(BASE_URL);console.log(url);const instance = injectorJerry.get(MY_SERVICE_TOKEN);console.log('MY SERVICE TOKEN: ', instance);}注意,我們也可以使用一個抽象類作為 injection token.
{ provide: MinimalLogger, useExisting: LoggerService },該 MinimalLogger 是一個抽象類。
// Class used as a "narrowing" interface that exposes a minimal logger // Other members of the actual implementation are invisible export abstract class MinimalLogger {abstract logs: string[];abstract logInfo: (msg: string) => void; }你通常從一個可擴展的抽象類繼承。但這個應用中并沒有類會繼承 MinimalLogger。
LoggerService 和 DateLoggerService本可以從 MinimalLogger 中繼承。 它們也可以實現 MinimalLogger,而不用單獨定義接口。 但它們沒有。 MinimalLogger 在這里僅僅被用作一個 "依賴注入令牌"。
當你通過這種方式使用類時,它稱作類接口。注意,如果我們這里將類接口替換成 interface,是無法工作的,因為 JavaScript 運行時根本不存在 interface 的概念。
就像 DI 提供者中提到的那樣,接口不是有效的 DI 令牌,因為它是 TypeScript 自己用的,在運行期間不存在。使用這種抽象類接口不但可以獲得像接口一樣的強類型,而且可以像普通類一樣把它用作提供者令牌。
類接口應該只定義允許它的消費者調用的成員。窄的接口有助于解耦該類的具體實現和它的消費者。
用類作為接口可以讓你獲得真實 JavaScript 對象中的接口的特性。 但是,為了最小化內存開銷,該類應該是沒有實現的。 對于構造函數,MinimalLogger 會轉譯成未優化過的、預先最小化過的 JavaScript。
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的使用Injection Token将字符串类型的参数注入到类的构造函数里的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iwatch1代还能用吗
- 下一篇: 手游吃鸡段位顺序