12

在 Angular 8 中,我能够使用“@Injectable”属性创建基础组件(实际组件继承自的类)。Angular 9 编译器告诉我:

组件 YourComponent 从 BaseComponent 继承其构造函数,但后者没有自己的 Angular 装饰器。依赖注入将无法解析 BaseComponent 的构造函数的参数。向 BaseComponent 添加一个 @Directive 装饰器,或者向 RoleSelectDialogComponent 添加一个显式构造函数。

现在 Angular 9 做这些事情的方式是什么?这可行,但看起来有点hacky:

@Component({
    selector: 'baseComponent',
    template: 'no-ui'
})
4

5 回答 5

14

线索在消息中

Either add a @Directive decorator to BaseComponent

向它添加 @Directive() 应该可以解决问题。

我现在正在升级,我的基础组件自动添加了 @Directive() 装饰器。

于 2020-02-07T15:25:12.397 回答
12

既然 Angular 10 已经发布并且警告现在是一个错误,这可能会影响到更多的人。

错误 NG2007:类正在使用 Angular 功能但未装饰。请添加一个明确的 Angular 装饰器。

此博客条目显示了一些示例https://volosoft.com/blog/what-is-new-in-angular-10


另外请注意,“Angular features”不仅仅意味着依赖注入。即使ngOnDestroy()在你的基类中存在也会触发这个。

我通过重命名ngOnDestroy()来解决它,_ngOnDestroy()并在销毁实际的@Injectable(). 如果我再次对它进行子类化并忘记调用,这似乎有点危险,_ngOnDestroy()但我不确定我有多少选择。

于 2020-06-27T17:44:58.927 回答
1

此模式已在 v9 中弃用,并且在 v10 中不再支持。

有一个迁移通常会自动迁移这些情况https://angular.io/guide/migration-undecorated-classeshttps://angular.io/guide/migration-injectable,但是可能是继承的 @Injectable( ) 案件未处理。

无论如何,这里的解决方案是将@Injectable() 添加到抽象基类中。

于 2020-09-09T14:36:56.307 回答
0

正如@Simon_Weaver 所说,您可能有一个父类,例如:

export class BaseComponent implements OnDestroy {
  protected subscriptions: Subscription[] = [];

  ngOnDestroy(): void {
    this.subscriptions.filter(sub => !!sub).forEach(subscription => {
      subscription.unsubscribe();
    });
  }
}

您可以这样做,而不是向每个孩子添加 ngOnDestroy:

/* tslint:disable */
@Directive()
export class BaseComponent implements OnDestroy {
  protected subscriptions: Subscription[] = [];

  ngOnDestroy(): void {
    this.subscriptions.filter(sub => !!sub).forEach(subscription => {
      subscription.unsubscribe();
    });
  }
}
于 2020-09-28T12:51:56.560 回答
0

您将需要向基类添加装饰器(@Directive)或删除由基类实现的任何 Angular 接口。在我将应用程序升级到 Angular 10 后,此错误开始出现。一个抽象基类正在实现 AngularOnInit接口。这个类后来被实际的组件类扩展。我没有添加无关的装饰器,而是OnInit从修复错误的基类中删除了实现。

于 2020-09-29T17:12:03.980 回答