在切换到Angular 5.2.3,并使用"deprecation": true
的林特规则运行ng cli
之后,我在许多测试中得到以下错误:
get is deprecated: from v4.0.0 use Type<T> or InjectionToken<T>
抱怨的行类似于
fixture.debugElement.injector.get(MyService)
其中MyService
是一个用于依赖注入的类。
我不知道新的语法应该是什么,因为
fixture.debugElement.injector.get<MyService>(MyService)
给出了一个编译错误,即Argument of type 'typeof MyService' is not assignable to parameter of type 'Type<MyService> | InjectionToken<MyService>'.
使用注入器以避免弃用错误的正确方法是什么?
编辑:有关Angular9更新,请参阅下面的答案。
编辑:这似乎与MyService是一个抽象类有关。如果我使用非抽象类,则.get<T>(T)
语法可以工作。
编辑:修复显然正在等待一些公关工作- https://github.com/angular/angular/pull/25222
发布于 2018-07-04 05:52:29
A更好的是,你可以尝试将你的服务转换为Type,然后像这样使用injector:
import { Type } from '@angular/core';
fixture.debugElement.injector.get<MyService>(MyService as Type<MyService>)
发布于 2018-05-05 00:02:44
作为临时修复,您可以尝试执行以下操作:
fixture.debugElement.injector.get<MyService>(MyService as any)
发布于 2018-08-02 12:58:19
我已经通过定义一个注入令牌来解决这个问题:
export const DATA_SERVICE = new InjectionToken('DataService');
并使用它在模块中为我的服务添加别名:
...
providers = [
{ provide: DataService, useFactory: dataServiceFactory },
{ provide: DATA_SERVICE, useExisting: DataService }
]
...
然后,我可以使用注入令牌直接从Injector
检索此服务,而不会收到弃用警告:
this.dataService = injector.get(DATA_SERVICE);
在我的例子中,DataService
是一个抽象类,我有两个具体的(@Injectable
)实现来在模拟数据和真实web服务数据之间切换。在dataServiceFactory
方法中实例化适当的版本。
injector.get()
调用有两个重载,我认为如果没有InjectionToken
,就会调用不推荐使用的重载,因为类型系统不会将typeof DataService
识别为InjectionToken
。
有趣的是,此服务通过构造函数对组件的所有注入,例如:
constructor(
ds: DataService
) { }
目前工作正常。当不推荐使用的get()
重载在将来被移除时,它们会工作吗?
我认为这是一个给Angular团队的问题。
https://stackoverflow.com/questions/48660938
复制相似问题