Benjamin Li Benjamin Li - 18 days ago 6
AngularJS Question

angularJS, after injecting service, it still reports unknow provider

I have injected the new service into my controller, but it always says unknown provider

my code:
export service:

class AlertService {
constructor($rootScope,$injector) {
this.rootScope = $rootScope;
this.injector = $injector;
}

showAlert(alertTitle='Alert',alertBody='') {
this.injector.get('$uibModal').open({
template: '<header><div class="alert-header"><h1>' + alertTitle + '</h1></div><div class="alert-close" ng-click="ok()"><i class="icon icon--close" aria-hidden="true"></i></div></header>'
+ '<section class="content-section content-section-alert"><p>' + alertBody + '</p></section>'
+ '<footer><button class="btn btn-primary" ng-click="ok()">ok</button>',
controller: function($scope, $uibModalInstance,$rootScope) {
$rootScope.ok = function() {
$uibModalInstance.dismiss('cancel');
};
},
windowClass: 'alert-modal'
});
}
}

AlertService.$inject = ['$rootScope','$injector'];

export default angular.module('services.alertService', [])
.service('alertService', AlertService)
.name;


inject the service into controller:

export default class StartController {
constructor($scope, alertService, $location){
this.alertService = alertService
this.scope = $scope
this.location = $location

this.watchUrl()
}

watchUrl() {
let url = this.location.url()
if(url.indexOf('start') == -1)
return

this.alertService.showAlert('alert','some error')
}
}
StartController.$inject = ['$scope', 'alertService', '$location'];


it would always report unknown provider:

Unknown provider: tProvider <- t


if I change the
alertService
to
alert()
, then it works

what would be the reason? thanks

Answer

You haven't provided dependency injection annotations for the modal's controller

controller: function($scope, $uibModalInstance, $rootScope) { ... }

Either extract it to a function or class so you can set the $inject property or use the array annotation, eg

controller: ['$scope', '$uibModalInstance', '$rootScope', 
            function($scope, $uibModalInstance, $rootScope) { ... }]