如何在Angular中使用生命周期钩子正确注释抽象基础组件

时间:2018-11-24 00:22:55

标签: angular

我有一个带有生命周期挂钩的抽象基础组件:

export abstract class BaseComponent implements OnChanges, OnInit {

  ngOnChanges(changes: SimpleChanges): void {
    …
  }

  ngOnInit() {
    …
  }
}

还有一个子组件:

@Component({
  …
})
export class ChildComponent extends BaseComponent {

这将导致Can't resolve all parameters for BaseComponent: (?, ?, ?).

该参数确实具有三个参数。所有三个值都在包含子组件的模块的providers部分中列出。无法将基础组件添加到模块,因为它与declarations所需的类型不兼容。

如果我将@Injectable()添加到BaseComponent,tslint会抱怨In the class "BaseComponent" which have the "@Injectable" decorator, the "ngOnChanges()" hook method is not allowed. Please, drop it. (contextual-life-cycle)。一切都很好。

@Component()添加到BaseComponent会导致Webstorm抱怨Component 'BaseComponent' is not included in a module and will not be available inside a template. Consider adding it to a NgModule declaration。同样,代码可以正常运行。

由于我喜欢使代码中没有任何警告:实现此模式的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

根本没有注释基础组件(@Injectable@Component都对我没有帮助)。

相关问题