Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何使用包装器';s类泛型类型?_Angular_Typescript - Fatal编程技术网

Angular 如何使用包装器';s类泛型类型?

Angular 如何使用包装器';s类泛型类型?,angular,typescript,Angular,Typescript,我使用angular 5,并且我试图减少在我的类中注入的参数数量。我不想讨论服务定位器是否是反模式,请理解angular/typescript是否允许我这样做 我经常使用service locator来解决这个问题,但有一个案例我不知道如何解决,我读到的关于通用注入的几个问题也没有多大帮助:/ 这是我的情况: export abstract class BaseComponent<T extends BaseModel> { protected recordId?: numb

我使用angular 5,并且我试图减少在我的类中注入的参数数量。我不想讨论服务定位器是否是反模式,请理解angular/typescript是否允许我这样做

我经常使用service locator来解决这个问题,但有一个案例我不知道如何解决,我读到的关于通用注入的几个问题也没有多大帮助:/

这是我的情况:

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

谢谢

如果您的环境中已经有一个注入器,您可以尝试以下方法:

protected store: Store<T>;

protected constructor() {
    this.store = AppInjectorService.injector.get<Store<T>>(Store);
}
受保护存储:存储;
受保护的构造函数(){
this.store=AppInjectorService.injector.get(store);
}

在Angular 6上测试。

如果您的环境中已经有喷油器,您可以尝试以下方法:

protected store: Store<T>;

protected constructor() {
    this.store = AppInjectorService.injector.get<Store<T>>(Store);
}
受保护存储:存储;
受保护的构造函数(){
this.store=AppInjectorService.injector.get(store);
}

在Angular 6上测试。

可能重复的请参见@estus对不起,我不同意这是重复的。我在这里发布之前阅读了相关的问题,这不是一回事。虽然第二个链接越来越近。如果你之前读过它们,你可能会知道不可能使用泛型,因此你有XY问题。问题的焦点是试图用泛型解决现有的问题,但对于真正的问题是什么还不够具体。它确实注入,但(很可能)由于angular的结构,它不代表当前路线-为什么是这样?你能提供吗?您可以将
baseType
构造函数作为route
data
传递。我建议以更具建设性的形式重新提问。好的,我将重新表述我的问题。关于路由,如果我使用服务定位器注入它,它并不代表当前路由。如果我通过构造函数注入它,如我的示例所示,它工作得很好,如果我尝试使用服务定位器,它并不表示当前路由。它不是空的,但它是“空的”。See@estus的可能副本我很抱歉,我不同意这是一个副本。我在这里发布之前阅读了相关的问题,这不是一回事。虽然第二个链接越来越近。如果你之前读过它们,你可能会知道不可能使用泛型,因此你有XY问题。问题的焦点是试图用泛型解决现有的问题,但对于真正的问题是什么还不够具体。它确实注入,但(很可能)由于angular的结构,它不代表当前路线-为什么是这样?你能提供吗?您可以将
baseType
构造函数作为route
data
传递。我建议以更具建设性的形式重新提问。好的,我将重新表述我的问题。关于路由,如果我使用服务定位器注入它,它并不代表当前路由。如果我通过构造函数注入它,如我的示例所示,它工作得很好,如果我尝试使用服务定位器,它并不表示当前路由。它不是空的,但它是“空的”。