Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
有没有办法仅通过服务名称获取 angular 2 的可注入服务的实例?
例如,在 Angular 1 中,您可以编写:
var service = $injector.get('ServiceName');
并且该service变量将获得该服务的一个实例。
service
我真的很感谢你们的帮助!
如果按名称提供,则可以按名称注入
@NgModule({ providers: [ ServiceName, {provide: 'ServiceName', useExisting: ServiceName} ], ...
您可以使用Injector Class使用显式注入器创建
injector = ReflectiveInjector.resolveAndCreate([ServiceClass, Dependency1Class, Dependency2Class]); let service= injector.get(ServiceClass); //pass the type not the name