Angular 角注入参数化提供程序

Angular 角注入参数化提供程序,angular,dependency-injection,angular-ivy,Angular,Dependency Injection,Angular Ivy,我有这样的服务 @Injectable() export class MyService { constructor(private store: Store, @Optional() type: string){} static forType(type: string) { return { provide: MyService, deps: [Store], useFactory: factoryFn.bind(type) } } } export funct

我有这样的服务

@Injectable()
export class MyService {
  constructor(private store: Store, @Optional() type: string){}

  static forType(type: string) {
    return { provide: MyService, deps: [Store], useFactory: factoryFn.bind(type) }  
  }

}

export function factoryFn(store: Store, type: string) {
  return new MyService(store, type);
}
@Component{ 
  providers: [MyService.forType('hello')]
}
export class MyComponent {}
@Component{ 
  providers: [MyService.forType('hello')]
}
export class MyComponent {}
想像这样把它注入我的组件吗

@Injectable()
export class MyService {
  constructor(private store: Store, @Optional() type: string){}

  static forType(type: string) {
    return { provide: MyService, deps: [Store], useFactory: factoryFn.bind(type) }  
  }

}

export function factoryFn(store: Store, type: string) {
  return new MyService(store, type);
}
@Component{ 
  providers: [MyService.forType('hello')]
}
export class MyComponent {}
@Component{ 
  providers: [MyService.forType('hello')]
}
export class MyComponent {}
但这给了我以下的错误

Function calls are not supported in decorators but 'factoryFn' was called in 'MyService'
'MyService' calls 'factoryFn'.
我希望将其作为实际服务上的静态方法的原因是,我不希望组件知道MyService需要哪些依赖项。MyService也在许多不同的地方使用,因此通过这种方式,我也避免了重复

有没有办法欺骗Angular允许函数调用


致以最良好的祝愿,Benedikt

经过一番搜索,我找到了一个很好的解决方法,可以解决这个问题。 我们可以基于我们想要的参数创建一个令牌,然后在服务中使用这个令牌。为了自动注入服务及其令牌,我们可以利用Angular将提供者数组展平的事实,这样我们就可以返回一个同时包含这两个内容的数组

export const MY_TOKEN = new InjectionToken<string>('MY_TOKEN');
@Injectable()
export class MyService {
  constructor(private store: Store, @Inject(MY_TOKEN) type: string){}

  static forType(type: string) {
    return [{ provide: MY_TOKEN, useValue: type}, MyService]
  }
}