Trevor Hector
Trevor Hector

Reputation: 639

Angular 2 - inherit providers from base class

I have the following BaseComponent.

@Component({
    providers: [PresetService, CollectionService, RecordService]
})
export class BaseComponent{
    constructor(private collectionService:CollectionService, private recordService:RecordService, private presetService:PresetService){
    }
}

Now all of the children should inherit the providers and it's instances:

I have the following BaseComponent.

@Component({ 
})
export class ChildComponent extends BaseComponent{
    constructor(){
        super()
    }
}

That doesn't seem to be possible, as I need to call super from the child. So I would need to pass to provider instances from child to base. Is it possible that the parent can provide the instances?

Upvotes: 6

Views: 2358

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657158

https://github.com/angular/angular/commit/f5c8e09

Decorators:

1) list the decorators of the class and its parents in the ancestor first order

2) only use the last decorator of each kind (e.g. @Component / ...)

Constructor parameters: If a class inherits from a parent class and does not declare a constructor, it inherits the parent class constructor, and with it the parameter metadata of that parent class.

Lifecycle hooks: Follow the normal class inheritance model, i.e. lifecycle hooks of parent classes will be called even if the method is not overwritten in the child class.

As workaround you could use

const baseComponentProviders = [PresetService, CollectionService, RecordService];

@Component({
    providers: baseComponentProviders
})
class BaseComponent {

}
@Component({ 
    providers: baseComponentProviders
})
export class ChildComponent extends BaseComponent{
    constructor(){
        super()
    }
}

Upvotes: 4

Related Questions