Injection With Inheritance in Aurelia

Aurelia 1

In Aurelia if you have a parent/base class and one or more children that inherit from this class AND the parent class has some injectables via Aurelia’s dependency injection container, you have most likely encountered an issue with needing to import and pass the dependencies back to the parent.

You might have done something like this:

import {inject} from 'aurelia-framework';
import {Router} from 'aurelia-router';

@inject(Router)
export class Parent {
    constructor(router) {
        this.router = router;
    }
}
import {Parent} from './parent';
import {Router} from 'aurelia-router';

@inject(Router)
export class Child extends Parent {
    constructor(router) {
        super(router);
    }
}

Gross.

Or maybe you imported the container directly and did this in your parent/base class:

import {Container} from 'aurelia-framework';
import {Router} from 'aurelia-router';

export class Parent {
    constructor() {
        this.router = Container.instance.get(Router);
    }
}

A little bit better, but still, there is no need to directly access the DI container for such a thing.

What if I told you there was a better way? Let’s use the spread operator and rest parameters to get our parent dependencies:

import {inject} from 'aurelia-framework';
import {Router} from 'aurelia-router';

@inject(Router)
export class Parent {
    constructor(router) {
        this.router = router;
    }
}
import {Parent} from './parent';

export class Child extends Parent {
    constructor(...rest) {
        super(...rest);
    }
}

Now what if you wanted to introduce a new dependency from within your child class? You can just do this:

import {inject} from 'aurelia-framework';
import {Router} from 'aurelia-router';

@inject(Router)
export class Parent {
    constructor(router) {
        this.router = router;
    }
}
import {inject} from 'aurelia-framework';
import {Parent} from './parent';

import {MyService} from './my-service';

@inject(MyService)
export class Child extends Parent {
    constructor(myService, ...rest) {
        super(...rest);
        this.myService = myService;
    }
}

You gotta love Aurelia, sometimes it feels like it makes some things a little TOO EASY.

Announcing Discover Aurelia

Update: I am working in recovering the site. I moved servers and some data was corrupted. The site will be down until it’s fixed. Since early …

Inline SVG Custom Element in Aurelia

A unique scenario popped up recently during a project I am building with Aurelia. I needed to cleanly be able to insert SVG images from a folder in my …