Skip to content

Instantly share code, notes, and snippets.

@sese
Last active August 31, 2016 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sese/198c268c3c38ac2d80413f51b9d12ccc to your computer and use it in GitHub Desktop.
Save sese/198c268c3c38ac2d80413f51b9d12ccc to your computer and use it in GitHub Desktop.

#Base Class

##before

import {AuthService} from './services/auth.service';
import {LocalStorage} from './services/localstorage.service';
import {Current} from './current';  

export class Base{
    
    constructor(){        
        this._authService = null;
        this._current = null;
        this._localStorage = null;        
    }    
    
    /**
     * @return a single instance of auth service
     */
    get authService() {
        if (!this._authService)
            this._authService = new AuthService;    
        return this._authService;
    }
    
    /**
     * @return a single instance of localstorage service
     */
    get localstorage(){
        if(!this._localStorage)
            this._localStorage = new LocalStorage;
        return this._localStorage;
    }
        
    /**
     * @return a single instance of current class
     */
    get current() { 
        if (!this._current)
            this._current = new Current;
        return this._current;
    }    
}    

##Pattern Issue:

You cannot inject base in AuthService. This DI pattern will fail:

@inject(Base);
export class AuthService {
    constructor(base) {
        this.base = base;
    }
    ...
}

@inject(AuthService);
export class Base {
    constructor(authService) {
        this.authService = authService;
    }
    ...
}

##after

import {inject} from 'aurelia-dependency-injection';

import {LocalStorage} from './services/localstorage.service';
import {Current} from './current'; 

@inject(LocalStorage, Current)
export class Base{
    
    constructor(storage, current){
        console.log("CONSTRUCTOR::Base");
        this._localStorage = storage;
        this._current = current;
    }

    /**
     * @return a single instance of localstorage service
     */
    get localstorage(){
        return this._localStorage;
    }
        
    /**
     * @return a single instance of current class
     */
    get current() {
        return this._current;
    }

}

#Usage

##before

import "Base" from "../base";

@inject(Base)
export Class Test{

    constructor(base) {
        this.base = base;  
    }
    
    logout(){
        this.base.authService.logout();
    }
        
}

##after:

import "AuthService" from "../service/auth.service";

@inject(authService)
export Class Test{

    constructor(authService) {
        this.authService = authService;  
    }
    
    logout(){
        this.authService.logout();
    }
        
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment