Mark Mark - 1 month ago 18
Javascript Question

Access a service in AngularUI Router onEnter callback

Im using Angular 1.5.6 and am using AngularUI Router (https://github.com/angular-ui/ui-router). I have different routes e.g. customer and users. In each of these there are different 'sub-roots' e.g. one for list and one for edt. Im setting up the customer route here:

import customerListModule from './list/customer.list';
import customerServiceModule from './services/customer.service';
...
...

function customerModule($stateProvider, $urlRouterProvider) {
'ngInject';

$urlRouterProvider
.when('/customer', ['$state', function($state) {
$state.go('customer.list.tracked');
}]);

$stateProvider
.state('customer', {
parent: 'root',
url: '/customer',
abstract: true,
views: {
'root@app': {
template: '<div class="customer" ui-view=""></div>'
}
},
onEnter: () => {
// in here I want to change my customer servce
},
})
.state('customer.list', {
url: '',
views: {
'@customer': {
template: '<customer></customer>'
}
},
breadcrumbs: {
name: 'customer.breadcrumbs.list'
},
params: {
saving: false
}
})
.state('customer.edit', {
parent: 'customer.list',
url: '/:id/edit',
views: {
'@customer': {
template: editTemplate(),
controller: manageCustomerCtrl,
controllerAs: 'manageCustomerVM'
}
},
breadcrumbs: {
name: 'customer.breadcrumbs.edit'
},
resolve: {
isAuthorized: 'readWriteAccess'
},
bodyClass: 'product-form'
});
}

export default angular.module('customerAdminUI.customer', [
'ui.bootstrap',
'ui.router',
customerListModule.name,
customerServiceModule.name,
...
...
])
.config(customerModule);


I have a customer service which I want to access in the onEnter callback of the customer state. I tried to inject it into the customerModule method so that I can use it in the onEnter() callback:

function customerModule($stateProvider, $urlRouterProvider, CustomerService) {

...
...


$stateProvider
.state('customer', {
parent: 'root',
url: '/customer',
abstract: true,
views: {
'root@app': {
template: '<div class="customer" ui-view=""></div>'
}
},
onEnter: () => {
CustomerService.clearSearch();
},
})


However I get the error:

Unknown provider: CustomerService


How can I use a service in the onEnter callback?

Answer

We can ask for a service as a param

// not ready for minification
onEnter: function(CustomerService) {
   CustomerService.dowhatneeded...
},

// preferred way
onEnter: ['CustomerService', function(service) {
   service.dowhatneeded...
}],
Comments