Angular 9 个带有 @Injectable() 的 BaseComponent

Angular 9 BaseComponent with @Injectable()

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

The component YourComponent inherits its constructor from BaseComponent, but the latter does not have an Angular decorator of its own. Dependency injection will not be able to resolve the parameters of BaseComponent's constructor. Either add a @Directive decorator to BaseComponent, or add an explicit constructor to RoleSelectDialogComponent.

Angular9 现在做这些事情的方法是什么?这行得通,但看起来有些怪异:

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

线索在消息中

Either add a @Directive decorator to BaseComponent

向其中添加一个@Directive() 应该可以解决问题。

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

现在 Angular 10 已经出来并且警告现在是一个错误,这可能会影响更多人。

error NG2007: Class is using Angular features but is not decorated. Please add an explicit Angular decorator.

这篇博文展示了一些例子https://volosoft.com/blog/what-is-new-in-angular-10


此外请注意 'Angular features' 不仅仅意味着依赖注入。即使你的基地 class 中存在 ngOnDestroy() 也会触发此事件。

我通过将 ngOnDestroy() 重命名为 _ngOnDestroy() 并在销毁实际 @Injectable() 时从子 class 调用它来解决它。如果我再次使用 subclass 并忘记调用 _ngOnDestroy(),这似乎有点危险,但我不确定我有多少选择。

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

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

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

正如@Simon_Weaver所说,您可能有一个 parent class 例如:

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

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

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

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

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

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