【问题标题】:Angular creating named instances of providersAngular 创建提供者的命名实例
【发布时间】: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


    【解决方案1】:

    正如@ghetolay 所建议的那样,我使用了InjectionToken 并且能够成功地创建多个命名提供程序作为工厂化实例:

    // 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 现在是这些提供程序实例的令牌。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多