如何代理使用DI的组件?

时间:2019-04-24 22:41:45

标签: angular typescript angular-dependency-injection

我正在尝试为Angular组件创建代理。从此解决方案开始: https://github.com/Microsoft/TypeScript/issues/4890#issuecomment-141879451

我最终得到了这个

interface Type<T> {
  new (...args): T;
}

interface Base {}

interface Identifiable {}

export function IdentifiableSubclass<T extends Base>(SuperClass: Type<T>) {
  class C extends (<Type<Base>>SuperClass) {
    // constructor(...args) {
    //   super(...args);
    //   return new Proxy(this, {
    //     get(target, name) {
    //       return target[name];
    //     }
    //   });
    // }
  }
  return <Type<Identifiable & T>>C;
}

用法:

@Component({...})
class HeroesComponent {
  constructor(public heroService: HeroService) {}
}
const HeroesComponentLogged = IdentifiableSubclass(HeroesComponent);
export { HeroesComponentLogged as HeroesComponent };

那行得通。问题是,如果我取消注释构造函数heroService is undefined,它将失败。

我认为这与Angular的DI有关,因为以下内容在TS Playground上运行良好(未评论构造函数):

class HeroService {
    public sayGoodbye() {
        console.log("Goodbye");
    }
}
class HeroComponent {
     constructor(public heroService: HeroService) {
    }
}

const IdentifiedHeroComponent = IdentifiableSubclass(HeroComponent);
let identified = new IdentifiedHeroComponent(new HeroService());
identified.heroService.sayGoodbye();

0 个答案:

没有答案