在他们的文档中,他们使用这个FactoryProvider
例子来升级 ajs 服务:
import { HeroesService } from './heroes.service';
export function heroesServiceFactory(i: any) {
return i.get('heroes');
}
export const heroesServiceProvider = {
provide: HeroesService,
useFactory: heroesServiceFactory,
deps: ['$injector']
};
@NgModule({
imports: [
BrowserModule,
UpgradeModule
],
providers: [
heroesServiceProvider
],
/* . . . */
})
有什么理由不这样做InjectionToken
吗providers
?
import { HeroesService } from './heroes.service';
import {inject, InjectionToken} from '@angular/core';
import {auto} from 'angular';
export const heroesServiceToken = new InjectionToken<HeroesService>('HeroesServices', {
providedIn: 'root',
factory() {
const $injector = inject('$injector' as any) as auto.IInjectorService;
const instance = $injector.get('heroes');
return instance as HeroesService;
}
});
...
import { HeroesService } from './heroes.service';
import {Inject} from '@angular/core';
class SomeComponent {
constructor(@Inject(heroesServiceToken) private heroesService: HeroesService) {
}
}