angularjs nie przewiduje żadnego mechanizmu wdrożenia dziedziczenie usług bezpośrednio, jednak w Twoim przypadku można użyć $provide.decorator przedłużyć BaseService
się lub używaj go jak prototyp innego ChildService
używając zwykłego JavaScript. W mojej praktyce, aby mieć usługę z konfigurowalnym stanem i zachowaniem, używam providers. We wszystkich poniższych przykładach wyjście konsoli będzie Świat.
Dekorator
Jeśli nie potrzebujesz oryginalnego BaseService
w module, można ozdobić go
Plunker
function AlertService() {
this.add = function(level, message) {
switch(level) {
case 'success':
console.log(message);
}
}
}
function BaseService(alertService) {
this.message = "Hello";
this.perform = function() {
alertService.add("success",this.message);
};
}
angular.
module('app',[]).
config(['$provide', function($provide) {
$provide.decorator('BaseService', function($delegate) {
$delegate.message = 'World';
return $delegate;
});
}]).
service('alertService', AlertService).
service('BaseService', ['alertService',BaseService]).
controller('ctrl', ['BaseService', function(baseService) {
baseService.perform();
}]);
prototypowa Dziedziczenie
Plunker
function AlertService() {
this.add = function(level, message) {
switch(level) {
case 'success':
console.log(message);
}
}
}
function BaseService(alertService) {
this.message = "Hello";
this.perform = function() {
alertService.add("success",this.message);
};
}
function ChildService(BaseService) {
angular.extend(ChildService.prototype, BaseService);
this.message = "World";
}
angular.
module('app',[]).
service('alertService', AlertService).
service('BaseService', ['alertService',BaseService]).
service('ChildService', ['BaseService',ChildService]).
controller('ctrl', ['ChildService', function(ChildService) {
ChildService.perform();
}]);
Provider
Plunker
function AlertService() {
this.add = function(level, message) {
switch(level) {
case 'success':
console.log(message);
}
}
}
function BaseService() {
var message = "Hello";
this.setMessage = function(msg) {
message = msg;
}
function Service(alertService) {
this.perform = function() {
alertService.add("success", message);
};
}
function Factory(alertService) {
return new Service(alertService);
}
this.$get = ['AlertService', Factory];
}
angular.
module('app',[]).
provider('BaseService', BaseService).
config(['BaseServiceProvider', function(baseServiceProvider) {
baseServiceProvider.setMessage('World');
}]).
service('AlertService', AlertService).
controller('ctrl', ['BaseService', function(baseService) {
baseService.perform();
}]);
Użyj ulubionego smaku dziedziczenia javascript, a następnie dodaj obiekty wynikowe jako usługi. Należy pamiętać, że ponieważ usługi są pojedyncze, należy dodać pojedynczą instancję lub konstruktora. – Sacho