【问题标题】:Angular 2: component with more than one dependencyAngular 2:具有多个依赖项的组件
【发布时间】:2015-09-06 16:16:16
【问题描述】:

以下代码:

...
@Component({
  selector: 'sitelink',
  properties: ['route: route, title: title, isHome: home, href: href']
})
@View({
  template: ''
})
export class SiteLink {
  constructor(@Optional() @Host() @SkipSelf() parentFrame: AppFrame, @Optional() @Host() @SkipSelf() parentLink: SiteLink) {
  }
...

在从 TypeScript 到 JavaScript 的翻译过程中出现以下错误

at line 32, file app-frame.ts Argument of type 'typeof SiteLink' is not assignable to parameter of type 'Type'.
Component({
  selector: 'sitelink',
  properties: ['route: route, title: title, isHome: home, href: href']
})
at line 36, file app-frame.ts Argument of type 'typeof SiteLink' is not assignable to parameter of type 'Type'.
View({
  template: ''
})

仅使用一个构造函数参数即可按预期工作。从参数列表中删除注释时,它也不起作用。删除 @Component@View 注释后,代码编译。所以这个错误肯定和@Component注解有关。 编辑:即使我将 SiteLink 参数替换为另一种类型(例如 AppFrame),我也会收到相同的错误。

我正在使用 alpha 36 和来自 distinctlyTyped 存储库的最新 d.ts 文件。

【问题讨论】:

  • 我不确定您尝试做的事情是否可行。在SiteLink 的构造函数中,您正在调用类本身。你确定这是你想要的吗?
  • 是的,我想获得父“SiteLink”组件。
  • 错误大概和这个problem一样。你用的是什么版本的打字稿?
  • 是的,这可能是问题所在。我正在使用 atom typescript 插件,它应该始终使用最新版本。

标签: javascript typescript angular


【解决方案1】:

可以通过使用前向引用在构造函数中注入类本身的实例:

constructor(@Inject(forwardRef(() => SiteLink)) siteLink) {
    this.name = nameService.getName();
}

更多详情请见here

【讨论】:

  • 这并不能解决问题。即使我将 SiteLink 参数替换为另一种类型,我也会收到相同的错误。
【解决方案2】:

正如 Jesse Good 所写,这是 angular 的 d.ts 文件的问题,请参阅 https://github.com/angular/angular/issues/3972

更换

  interface Type extends Function {
     new(args: any): any;
  }

  interface Type extends Function {
     new(...args): any;
  }

帮我修好了。

【讨论】:

    猜你喜欢
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 2017-08-21
    • 2017-12-27
    相关资源
    最近更新 更多