5
votes

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:

  1. Is this a current known limitation of Angular2's Component Inheritance support?
  2. Is there something missing/wrong with this code sample?
  3. Is this a bug with Angular2's support for Component Inheritance?
1
why are you using inheritance in your components? - shusson
I misread your question. This is not parent and child but sub and superclass. - Günter Zöchbauer
@Gunter can you clarify? In my experience, parent is to child as superclass is to subclass (when the relationship tree is 2-deep). Am I missing something? - The Aelfinn
A parent component is hosting the child component in it's view. A subclass extends a superclass and inherits it's implementation. These two are entirely different concepts. - Günter Zöchbauer
You are correct. An Angular2 child component can be nested within an Angular2 parent component, in a "parent-child" component relationship. The relationship in this post refers to a general (non-Angular) inheritance pattern between a Parent & Child class. (Also referred to as "Super and Subclass".) I have updated the question title to avoid confusion. - The Aelfinn

1 Answers

1
votes

Make it public or protected, i.e.

constructor(protected _my_service: MyService){};

if you do not use in the constructor protected, private, or public, for example, DI, the range of the variable _my_service is the scope of the constructor { } 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.