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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With