Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inherit Injected service from superclass into subclassed component in Angular 2

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?
like image 249
The Aelfinn Avatar asked Nov 09 '22 03:11

The Aelfinn


1 Answers

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.

like image 73
Roman C Avatar answered Nov 15 '22 06:11

Roman C