Angular 9 BaseComponent with @Injectable()

ε祈祈猫儿з 提交于 2020-06-29 03:49:16

问题


In Angular 8 I was able to create base components (classes the actual component inhert from) with an "@Injectable" attribute. The Angular 9 compiler tells me:

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.

What is the Angular 9 way of doing these things now? This works but looks somehow hacky:

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

回答1:


The clue is in the message

Either add a @Directive decorator to BaseComponent

Adding a @Directive() to it should do the trick.

I'm just going through an upgrade now, and my base component automatically has the @Directive() decorator added.




回答2:


This is probably going to hit more people now that Angular 10 is out and the warning is now an error.

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

This blog entry shows some examples https://volosoft.com/blog/what-is-new-in-angular-10


In addition please note that 'Angular features' doesn't just mean dependency injection. Even the presence of ngOnDestroy() in your base class will trigger this.

I solved it by renaming ngOnDestroy() to _ngOnDestroy() and called it from the subclass on destruction of the actual @Injectable(). This seems a little dangerous if I were to ever subclass it again and forgot to call _ngOnDestroy() but I'm not sure I had much choice.



来源:https://stackoverflow.com/questions/60116361/angular-9-basecomponent-with-injectable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!