[英]How to get generic service using wrapper's class generic type?
我正在使用角度5,並嘗試減少在類中注入的參數數量。 我不是要討論服務定位器是否是反模式,請理解angular / typescript是否允許我這樣做。
我經常使用服務定位器,但是有一種情況我不知道如何解決,而我讀到的有關泛型注入的一些問題並沒有太大幫助:/
這是我的情況:
export abstract class BaseComponent<T extends BaseModel> {
protected recordId?: number = undefined;
protected alertService: AlertService;
protected translateService: TranslateService;
protected router: Router;
protected constructor(
protected activatedRoute: ActivatedRoute,
protected store: BaseCrudStore<T>,
protected baseType: { new(): T; }
) {
this.record = new baseType();
this.alertService = ServiceLocator.injector.get(AlertService);
this.translateService = ServiceLocator.injector.get(TranslateService);
this.router = ServiceLocator.injector.get(Router);
//...
}
}
我希望也可以使用服務定位器來解決BaseCrudStore
,而不是通過構造函數注入它。 有沒有辦法做到這一點? 有沒有辦法使用服務定位器進入我的商店? 如您所見, BaseCrudStore
也是通用的,並且通用參數與BaseComponent
類相同。
到目前為止,我還不能修復注入ActivatedRoute
。 它確實注入了,但是(很有可能)由於角度的結構,它不代表當前路線,這對於思考它的建造方式是有道理的。 如果您知道如何也解決此問題:)
我對此表示感謝,我的代碼正在100%正常工作,這只是困擾我幾個月的事情,我無法修復。
ServiceLocator初始化:
export class AppModule {
constructor(private injector: Injector) {
ServiceLocator.injector = this.injector;
}
}
謝謝!
如果您的環境中已經裝有注射器,則可以嘗試以下操作:
protected store: Store<T>;
protected constructor() {
this.store = AppInjectorService.injector.get<Store<T>>(Store);
}
在Angular 6上測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.