如何使用Inject获得一次服务实例 [英] How to get once instance of service with Inject
问题描述
如何使用Injector获得相同的单例服务实例:
我在引导应用程序上定义了此服务的提供程序(对于所有应用程序中的一个实例)
I define provider of this service on the bootstrap application(for one instance on the all application)
示例:
//Init application
bootstrap(AppComponent, [ROUTER_PROVIDERS, HTTP_PROVIDERS, SessionService]);
SessionService
Singleton-这只是示例,但实际上可以是会话或ACL服务
SessionService
Singleton - this is just example, but in real can be session or acl service
@Injectable()
export class SessionService {
constructor() {
console.warn("INSTANCE OF SESSION SERVICE-a");
}
public getInstance(instanceName: string){
console.warn("Injected service come from component name: " + instanceName);
}
}
SecuredHomeComponent
当我在构造函数上注入服务时,只有一次服务实例(良好)
@Component()
@CanActivate(AccessService.checkSession)
export class SecuredHomeComponent {
public constructor(private testSessionService: SessionService) {
this.testSessionService.getInstance('Component1:1'); //Test 1 - get the same instance when service is inject into contructor
}
}
MyStaticService
我这样尝试,注入服务,但是一直都得到新的服务实例 但是我需要使用"Injector.resolveAndCreate"直接注入到静态方法中,然后NG2创建新的服务实例(错误)
MyStaticService
I try like this, inject service but All the time get new Instance of service But I need inject directly into for example static method using "Injector.resolveAndCreate" then NG2 create new Instance of service (bad)
@Injectable()
export class MyStaticService {
public static getDataFromService() {
//That two ways is bad, bcs create new instance of my test SessionService
//Test4
let providers = Injector.resolve([ SessionService ]);
let injectorFirst = Injector.fromResolvedProviders(providers);
let testServFirst = injectorFirst.get(SessionService);
testServFirst.getInstance('StaticService1:1');
//Test 5
let injectorSecond = Injector.resolveAndCreate([SessionService]);
let testServSecond = injectorSecond.get(SessionService);
testServSecond.getInstance('StaticService1:2');
}
}
静态服务
对于真实的例子,我需要带有静态方法的静态类 如果我能很好地理解文档,那么当要覆盖注释的方法时 canActivate 必须为服务提供静态方法
Static Service
For real example, I need static class with static method If I good understand doc, when want overwrites methods for annotation canActivate must provide servise with static method
行:我的"SecuredHomeComponent"中的@CanActivate(AccessService.checkSession)
Line: @CanActivate(AccessService.checkSession) in my "SecuredHomeComponent"
//Static Service - ACCESS
@Injectable()
export class AccessService {
public static checkAccess = (next: ComponentInstruction, prev: ComponentInstruction): boolean => {
return AccessService.checkSession() && AccessService.checkAcl(res, priv);
}
public static checkSession(): boolean {
let injectedSessionServices: SessionService; //How to inject the same instance of my SessionService?
return injectedSessionServices.getDataFromService(); //for real service he get back checkSession from sessionService
}
public static checkAcl(aclResource: AclResources, aclPrivilege: AclPrivileges): boolean {
let injectedAclServices: SessionService; //How to inject the same instance of my SessionService?
return injectedAclServices.checkAcl(aclResource, aclPrivilege);
}
}
推荐答案
我发现使用一个全局服务实例的解决方案 injector 通过 getInstance()实现了标准单例类进入引导应用程序.然后,可以在所有应用程序级别上获得注入服务的简单实例.如果有一段时间有人找到不同的解决方案,或者NG2解决了这个不同的问题,请告诉我.
I find solution with using one instance of global service injector implemented standard singleton class with getInstance() into bootstrap application. And after that can get simple instance of injected service on all level of application. If some time somebody find different solution, or NG2 resolve this different pls let me know.
非常简单的示例的示例代码:
Bootstrap应用程序
Bootstrap app
//Init application
bootstrap(AppComponent, [ROUTER_PROVIDERS, MY_PROVIDERS, HTTP_PROVIDERS])
.then((appRef) => MainInjectorService.getInstance().setInjector(appRef.injector));
我的助手主注射器
import { Injector, Injectable } from 'angular2/src/core/di';
@Injectable()
export class MainInjectorService
{
static instance:MainInjectorService;
static isCreating:Boolean = false;
private _injector: Injector;
constructor() {
if (!MainInjectorService.isCreating) {
throw new Error("You can't call new in Singleton instances!");
}
}
public static getInstance() {
if (MainInjectorService.instance == null) {
MainInjectorService.isCreating = true;
MainInjectorService.instance = new MainInjectorService();
MainInjectorService.isCreating = false;
}
return MainInjectorService.instance;
}
public setInjector(injector: Injector) {
this._injector = injector;
}
public getInjector(): Injector {
return this._injector;
}
}
我的STATIC课程
// Access - static service
@Injectable()
export class StaticAccessService {
// Get service instance from global provides service
private static _getService<T>(serviceName: any) {
let injector: Injector = MainInjectorService.getInstance().getInjector();
return injector.get(serviceName);
}
//Check access to session and acl
public static checkAccess = (next: ComponentInstruction, prev: ComponentInstruction): boolean => {
return StaticAccessService.checkSession() && StaticAccessService.checkAcl(next.routeData.data['res'], next.routeData.data['priv']);
}
// Check session access
public static checkSession(): boolean {
return StaticAccessService._getService(MySessionService).checkSession();
}
// Check session access
public static checkAccess(res, priv): boolean {
return StaticAccessService._getService(MyAclService).checkAccess(res, priv);
}
}
以及如何在组件中使用
@Component()
@CanActivate(StaticAccessService.checkAccess)
export class SecuredComponent {
}
这篇关于如何使用Inject获得一次服务实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!