2017-05-09 70 views
1

在Angular中,我有一項訪問緩存的服務。該服務大致如此工作(但具有更多異步行爲)。Angular創建提供者的命名實例

@Injectable() 
export class Cache { 

    cache : CacheTable; 

    constructor(
    protected name : string 
) { 
    this.cache = this.getTable(name); 
    } 

    put(id:string, data:any):void { this.cache.put(id, data); } 
    get(id:string):any { return this.cache.get(id); } 

    getTable(name : string) : CacheTable; 

} 

現在我有一些像UserService服務,希望能有一個Cache對應new Cache('user');的。命名ImageService另一項服務應與對應new Cache('image');

Cache實例對於這個工作,我想創建一個工廠來提供這些:

// file: custom-caches.ts 

import { Provider } from '@angular/core'; 
import { Cache } from '../cache/cache'; 

export let userCache : Provider = { 
    provide: Cache, 
    useFactory:() => new Cache('user') 
}; 

export let imageCache : Provider = { 
    provide: Cache, 
    useFactory:() => new Cache('image') 
}; 

我怎麼會去註冊和使用這些服務的?據我所知,他們都註冊爲'Cache'。

// file: my.module.ts 

@NgModule({ 
    providers: [userCache, imageCache] 
}) 
export class MyModule {} 

(這涉及到my other question

回答

0

如所建議的通過@ghetolay我用InjectionToken,並能成功地創建多個命名提供商factoried實例:

// file: custom-caches.ts 

import { Provider } from '@angular/core'; 
import { Cache } from '../cache/cache'; 

export const UserCache = new InjectionToken('userCache'); 

export let userCacheProvider : Provider = { 
    provide: UserCache, 
    useFactory:() => new Cache('user') 
}; 

export const ImageCache = new InjectionToken('imageCache'); 

export let imageCacheProvider : Provider = { 
    provide: ImageCache, 
    useFactory:() => new Cache('image') 
}; 

_

// file: my.module.ts 

@NgModule({ 
    providers: [userCacheProvider, imageCacheProvider] 
}) 
export class MyModule {} 

_

// file : UserService 

@Injectable() 
export class UserService { 
    constructor(
    @Inject(UserCache) private cache : Cache 
) {} 
} 

UserCacheImageCache現在令牌爲這些供應商的情況。

相關問題