【发布时间】:2017-10-07 19:53:38
【问题描述】:
在 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,它们希望有一个与new Cache('user'); 对应的Cache。另一个名为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有关)
【问题讨论】:
标签: angular factory angular-providers angular-factory