简体   繁体   English

如何使用包装器的类通用类型获取通用服务?

[英]How to get generic service using wrapper's class generic type?

I'm using angular 5 and I'm trying to lower the amount of parameters are injected in my classes. 我正在使用角度5,并尝试减少在类中注入的参数数量。 I'm not looking to discuss if service locator is an anti-pattern or not, just understand if angular/typescript would allow me to do that, please. 我不是要讨论服务定位器是否是反模式,请理解angular / typescript是否允许我这样做。

I use service locator for that quite often, but there's one case I can't figure out how to solve and the few questions I read about generic injection did not help much :/ 我经常使用服务定位器,但是有一种情况我不知道如何解决,而我读到的有关泛型注入的一些问题并没有太大帮助:/

Here's my case: 这是我的情况:

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);
        //...
   }
}

I'd like BaseCrudStore to also be resolved using service locator instead of injecting it through the constructor. 我希望也可以使用服务定位器来解决BaseCrudStore ,而不是通过构造函数注入它。 Is there a way to accomplish this? 有没有办法做到这一点? Is there a way to get my store using the service locator? 有没有办法使用服务定位器进入我的商店? As you can see, the BaseCrudStore is also generic and the generic parameter is the same one of the BaseComponent class. 如您所见, BaseCrudStore也是通用的,并且通用参数与BaseComponent类相同。

So far I can't also fix injecting ActivatedRoute . 到目前为止,我还不能修复注入ActivatedRoute It does inject, but (very likely) because of angular's structure it does not represent the current route, which makes sense thinking how it is built. 它确实注入了,但是(很有可能)由于角度的结构,它不代表当前路线,这对于思考它的建造方式是有道理的。 If you know how to also fix this :) 如果您知道如何也解决此问题:)

I appreciate any help on this... my code is working 100%, it's just something that's been bothering me for a few months and I couldn't fix it. 我对此表示感谢,我的代码正在100%正常工作,这只是困扰我几个月的事情,我无法修复。

ServiceLocator init: ServiceLocator初始化:

export class AppModule {
    constructor(private injector: Injector) {
        ServiceLocator.injector = this.injector;
    }
}

Thanks! 谢谢!

If you already have an injector in your environment, you can try something like this: 如果您的环境中已经装有注射器,则可以尝试以下操作:

protected store: Store<T>;

protected constructor() {
    this.store = AppInjectorService.injector.get<Store<T>>(Store);
}

Tested on Angular 6. 在Angular 6上测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM