AngularJS 服务:
app.service('NameService', function() {
this.name = function (name) {
return "Hello " + name;
}
});
角度升级:
import { InjectionToken } from "@angular/core";
export const NameService = new InjectionToken<any>('NameService');
export function nameServiceFactory(i: any): any {
return i.get('NameService');
}
export const nameServiceProvider = {
provide: NameService,
useFactory: nameServiceFactory,
deps: ['$injector']
};
现在我可以在 Angular 组件或管道中使用该服务:
@Pipe({
name: 'name',
pure: false
})
export class NamePipe implements PipeTransform {
constructor(@Inject(NameService) private nameService: any) { }
transform(value: any, args?: any): any {
// can use this.nameService here
}
}
我在测试这个管道时遇到了问题。
describe('NamePipe', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [],
providers: [nameServiceProvider],
declarations: [NamePipe]
})
.compileComponents();
}));
it('create an instance', () => {
const service: any = TestBed.get(NameService);
const pipe = new NamePipe(service);
expect(pipe).toBeTruthy();
});
});
这会引发以下错误:
NullInjectorError:$injector 没有提供者!
我曾尝试在createAngularJSTestingModule和createAngularTestingModule上查看https://angular.io/api/upgrade/static/testing/ , 但没有任何运气。
一旦我将 AngularJS 模块拉入测试,我就会收到错误消息,即没有加载程序来处理 angularJS 模块中的 .html 文件类型。
如何将升级的 AngularJS 服务注入 Angular 测试组件?