As of Angular v2.0, inheritance is supported between components.
Given a parent class, with a service provided to the constructor via dependency-injection, is it possible to define a child class which extends (or inherits) its parent class, such that it can access the parent's service?
import {MyService} from './my.service'
import {OnInit} from '@angular/core'
@Component({
selector: 'parent-selector',
providers: [MyService],
templateUrl: 'my_template.html'
})
export class ParentClass implements OnInit{
public foobar: number;
constructor(protected _my_service: MyService){};
ngOnInit(){
foobar = 101;
}
}
@Component({
selector: 'child-selector',
templateUrl: 'my_template.html'
})
export class ChildClass extends ParentClass{
public new_child_function(){
// This prints successfully
console.log(this.foobar);
// This throws an error saying my_service is "undefined"
this._my_service.service_function();
}
}
When we try and call new_child_function()
from the child class, it succesfully accesses its parent's member foobar, but the call to this._my_service.service_function()
gives us the following not-so-fun error:
Cannot read property 'get' of undefined
It appears the parent-injected service is not available to the child in this specific case. I am wondering:
Make it public
or protected
, i.e.
constructor(protected _my_service: MyService){};
if you do not use in the constructor
protected
,private
, orpublic
, for example, DI, the range of the variable_my_service
is the scope of theconstructor { }
you could not use from another function.
You can read more about Parameter properties and how they are declared and accessed.
Parameter properties are declared by prefixing a constructor parameter with an accessibility modifier or
readonly
, or both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With