Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to load dependencies in a controller super class of an AngularJS application?

I am building an AngularJS application that provides basic CRUD features. That app is built using TypeScript to take advantage of types and classes. I have a base controller that needs access to several AngularJS dependencies. Originally, I injected the dependencies as follows

File: base-controller.ts

class BaseController {
    private $location;
    private $routeParams;
    constructor($location, $routeParams) {
        /* Manually inject dependencies */
        this.$location = $injector.get('$location');
        this.$routeParams = $injector.get('$routeParams ');
    }
}

File: list-controller.ts

class WorkRequestListController extends BaseController {
    /* Write code to override base controller or implement local methods */
}

angular.module('app.workRequests')
    .controller('WorkRequestListController', ['$location', '$routeParams',
        ($location, $routeParams) => new WorkRequestListController($location, $routeParams)
]);

This solution works, but requires my subclass to be aware of the dependencies required by my base class. If I ever need another dependency in my base class, I would have to change every subclass and the statement which instantiates the controller. To fix these issues, I now simply pass $injector into my base class as follows:

File: base-controller.ts

class BaseController {
    private $location;
    private $routeParams;
    constructor($injector) {
        /* Load dependencies */
        this.$location = $injector.get('$location');
        this.$routeParams = $injector.get('$routeParams');
    }
}

File: list-controller.ts

class WorkRequestListController extends BaseController {
    /* Write code to override base controller or implement local methods */
}

angular.module('app.workRequests')
    .controller('WorkRequestListController', ['$injector',
        ($injector) => new WorkRequestListController($injector)
]);

Here's my question: Is this the correct way to load dependencies in a super class without forcing the subclass or other code to be aware of the dependencies?

like image 657
Bob Cardenas Avatar asked Sep 30 '22 12:09

Bob Cardenas


1 Answers

Is this the correct way to load dependencies in a super class without forcing the subclass or other code to be aware of the dependencies?

This is a way. Angular doesn't recommend inheritance in controllers. It prefers composistion. The common functionality should go in a service/factory that gets injected into your controllers.

like image 104
basarat Avatar answered Oct 18 '22 01:10

basarat