Ionic2: How inject dependencies in a global class?


#1

Hi!
I have some pages in my app (page1,page2 page3) which extends a global class called basePage.

How inject dependencies in this basePage? i can’t inject them by constructor(), i get some conflicts when i call super() in each child pages…

if i want inject my providers by constructor, i must inject them first in my child page:

childPage:

export class page1 extends basePage {
    constructor(private nav: NavController) {
        super(nav);
    }
}

basePage:

constructor(nav) {
        this._nav = nav;
        this._nav.setRoot(...);
}

So, how can i directly inject my dependencies in basePage?:

import { NavController} from 'ionic-angular';
constructor() {
    this._nav = MAGICMETHODINJECTION(NavController)
    this._nav.setRoot(...)
}

Thank you.


#2

I think inheritance is an overrated concept in general, and especially so in JavaScript. Can you achieve your overall goal using composition instead?


#3

It’s seem easier to inject all my dependencies in each pages… i just need another way to inject all my depencies, not inside constructor, is there a method to do that, or we must put them in contructor parameters?


#4

Why? You are being very coy about what you are really trying to achieve, which makes it hard to help you.


#5

Dependency injection in the contructor is only a very short form of that what really happens .

but it would be a mess not to do it in the constructor.

And inheritance will not really work for angular components / ionic pages.


#6

If i understand good, not use constructor to inject my dependecies could be dangerous and make my app unstable? So, if i want make a global page,
which groups some methods and properties used in all my pages, it’s better to inject all dependecies i need in this global in all pages and then pass them by inheritance in my “super()” call?

Thank you


#7

Inheritance will not work for components in ionic rc4.

You will need angular >= 2.3 for that.


#8

I still don’t understand why OP is so attached to using inheritance here.