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)