Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 9 BaseComponent with @Injectable()

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'
})
like image 422
tris Avatar asked Feb 07 '20 15:02

tris


People also ask

What is injectable () in Angular?

The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism.

Is it mandatory to use injectable on every service class?

No. The @Injectable() decorator is not strictly required if the class has other Angular decorators on it or does not have any dependencies. But the important thing here is any class that is going to be injected with Angular is decorated.

What is Providedin in injectable?

providedInlinkDetermines which injectors will provide the injectable.

How is Angular Dependency Injection implemented?

The first step is to add the @Injectable decorator to show that the class can be injected. The next step is to make it available in the DI by providing it. A dependency can be provided in multiple places: At the Component level, using the providers field of the @Component decorator.


1 Answers

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.

like image 178
Kurt Hamilton Avatar answered Oct 12 '22 12:10

Kurt Hamilton