I started using ocLazyload to lazy load few of my AngularJs controllers. I have used it along with the $routeProvider like this
$routeProvider.when("/login", {
templateUrl: "login.html",
resolve: {
loadCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load('LoginCtrl.js');
}]
}
}).
and this works fine.
I have another route definition which uses resolve property to resolve few items before loading the controller.
when("/dashboard", {
templateUrl: "dashboard.html",
controller: "DashboardCtrl",
resolve: {
profileData: getProfile,
count : getCount
}
}).
Now I want to lazy load this controller too, and I tried it like this
when("/dashboard", {
templateUrl: "dashboard.html",
resolve: {
profileData: getProfile,
count : getCount,
loadCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load(['DashboardCtrl.js']);
}]
}
}).
The page loads in this case, but the profileData and count doesn't get injected into the controller. The controller definition is as given below.
var app = angular.module('gt');
app.controller('DashboardCtrl', ['$scope', '$rootScope', 'profileData', 'count',
function($scope, $rootScope, profileData, count) {
...
}]);
On debugging, I realise that the getProfile and getCount method get's called, but it happens asynchronously and the controller also lazy loads without waiting for these methods. How do I inject and lazy load at the same time? Can I use promises to resolve this in any way?
I am using AngularJS 1.3.10 & ocLazyLoad 1.0.5 versions
getProfile function for reference
var getProfile = function($q, $http, Profile, localStorageService) {
var deferred = $q.defer();
if (!localStorageService.get("loggedInUser")) {
$http.post('/loggedin').success(function(user) {
if (user) {
localStorageService.set("loggedInUser", user.email)
Profile.get(localStorageService.get("loggedInUser"), function(profileData) {
if (profileData) {
deferred.resolve(profileData);
} else {
deferred.resolve();
}
});
} else {
deferred.reject();
}
});
} else {
Profile.get(localStorageService.get("loggedInUser"), function(profileData) {
if (profileData) {
deferred.resolve(profileData);
} else {
deferred.resolve();
}
});
}
return deferred.promise;
}
getProfile.$inject = ["$q", "$http", "Profile", "localStorageService"];
I could get this working with the following configuration of $routeProvider
when("/dashboard", {
templateUrl: "dashboard.html",
controller :"DashboardCtrl"
resolve: {
profileData: getProfile,
count : getCount,
loadCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load(['DashboardCtrl.js']);
}]
}
}).
where DashboardCtrl is the controller defined in DashboardCtrl.js
does getProfile and getCount return a promise? I would guess this is the problem as this is required. Every object put in resolve should return a promise. see the documention
If you need your resolves to happen in a specific order, you can inject them into another resolve, like this:
when("/dashboard", {
templateUrl: "dashboard.html",
resolve: {
profileData: getProfile,
count : getCount,
loadCtrl: ['$ocLazyLoad', 'profileData', 'count', function($ocLazyLoad, profileData, count) {
return $ocLazyLoad.load(['DashboardCtrl.js']);
}]
}
}).
Related
I want to verify if the user can access a state before he gets there, if he doesn't have permissions will be redirected to another page.
The problem is that I'm doing a SPA and it verifies the permissions, but it takes a while until the server send the response and the user is redirected, so what happen is that a screen appears for 1 or 2 seconds and then is redirected successfully. Is there anyway to avoid this?
This is the code for the state change:
webApp.run(function ($rootScope, $state, StateService) {
$rootScope.$on('$stateChangeStart', function (event, toState, fromState, toParams) {
StateService.hasAccessTo(toState.name, function(data){
if (data.data != ""){
event.preventDefault();
$state.go(data.data);
}
});
});
});
and the service:
webApp.service('StateService', function($http, $rootScope){
this.hasAccessTo = function(state, callback){
$http.get("state/" + state).then(callback);
}
});
I have also tried with a promise in the $stateChangeStart, but it didn't work.
I read about interceptors, but they work if the user is in another page and access mine, if he is already on the page and type a link manually it doesn't intercepts.
Any modifications or suggestions of new ideas or improvements are welcome!
EDIT
Now I have this:
var hasAccessVerification = ['$q', 'StateService', function ($q, $state, StateService) {
var deferred = $q.defer();
StateService.hasAccessTo(this.name, function (data) {
if (data.data !== '') {
$state.go(data.data);
deferred.reject();
} else {
deferred.resolve();
}
});
return deferred.promise;
}];
$urlRouterProvider.otherwise("/");
$compileProvider.debugInfoEnabled(false);
$stateProvider
.state('welcome',{
url:"/",
views: {
'form-view': {
templateUrl: '/partials/form.html',
controller: 'Controller as ctrl'
},
'#': {
templateUrl: '/partials/welcome.html'
}
},
data: {
requireLogin: false
},
resolve: {
hasAccess: hasAccessVerification
}
})
And it validates, but it doesn't load the template. It doesn't show de views. What might I be doing wrong?
EDIT 2
I forgot to add $state here:
var hasAccessVerification = ['$q', '$state', 'StateService', function ($q, $state, StateService){...}
Consider using the resolve in your state configuration instead of using $stateChangeStart event.
According to the docs:
If any of these dependencies are promises, they will be resolved and
converted to a value before the controller is instantiated and the
$stateChangeSuccess event is fired.
Example:
var hasAccessFooFunction = ['$q', 'StateService', function ($q, StateService) {
var deferred = $q.defer();
StateService.hasAccessTo(this.name, function (data) {
if (data.data !== '') {
$state.go(data.data);
deferred.reject();
} else {
deferred.resolve();
}
});
return deferred.promise;
}];
$stateProvider
.state('dashboard', {
url: '/dashboard',
templateUrl: 'views/dashboard.html',
resolve: {
hasAccessFoo: hasAccessFooFunction
}
})
.state('user', {
abstract: true,
url: '/user',
resolve: {
hasAccessFoo: hasAccessFooFunction
},
template: '<ui-view/>'
})
.state('user.create', {
url: '/create',
templateUrl: 'views/user/create.html'
})
.state('user.list', {
url: '/list',
templateUrl: 'views/user/list.html'
})
.state('user.edit', {
url: '/:id',
templateUrl: 'views/user/edit.html'
})
.state('visitors', {
url: '/gram-panchayat',
resolve: {
hasAccessFoo: hasAccessFooFunction
},
templateUrl: 'views/visitor/list.html'
});
And according to the docs https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#inherited-resolved-dependencies resolve are inherited:
New in version 0.2.0
Child states will inherit resolved dependencies from parent state(s),
which they can overwrite. You can then inject resolved dependencies
into the controllers and resolve functions of child states.
But, please note:
The resolve keyword MUST be on the state not the views (in case you
use multiple views).
The best practice is to have interceptor on responseError which checks the response status and acts accordingly:
webApp.config(['$httpProvider' ($httpProvider) {
var interceptor = ['$q', '$rootScope', function ($q, $rootScope) {
return {
request: function (config) {
// can also do something here
// for example, add token header
return config;
},
'responseError': function (rejection) {
if (rejection.status == 401 && rejection.config.url !== '/url/to/login') {
// If we're not on the login page
$rootScope.$broadcast('auth:loginRequired');
}
}
return $q.reject(rejection);
}
}
}];
$httpProvider.interceptors.push(interceptor);
}]);
And handle redirection in run block
webApp.run(['$rootScope', function($rootScope){
$rootScope.$on('auth:loginRequired', function () {
$state.go('loginState');
});
}]);
The good thing is that $state service does not need to deal with permission logic:
$stateProvider
.state('someState', {
url: '/some-state',
templateUrl: '/some-state.html',
resolve: {
dataFromBackend: ['dataService', function (postingService) {
// if the request fails, the user gets redirected
return dataService.getData();
}],
},
controller: function ($scope, dataFromBackend) {
}
})
Notice
With this approach, you do not need StateService, all you need to do is to return proper response statuses from backend. For example, if the user is guest, return 401 status.
I'm using ui-router in my app.
app.config(['$stateProvider', function($stateProvider){
$stateProvide.state('State1', {
url:'/State1',
resolve: {
data: function(Service){
return Service.init();
}
},
views: {
"header": {
templateUrl: 'views/header.tpl.html'
},
"center":{
templateUrl: 'views/center.tpl.html'
},
"footer": {
templateUrl: 'views/footer.tpl.html'
}
}
}
})
}
]);
I tried to load a json file from the server and resolve it in the router.
In the resolve object, I call to my service that is responsible for returning promise.
Service.js:
app.service("Service", ['$rootscope', '$http', function($rootscope, $http){
var promise;
this.init = function(){
promise = this.loadData();
return promise;
};
this.loadData = function(){
var url = "users/getData/json.json";
return $http.get(url).then(function(response){
return response.data;
}, function(error){
alert(error);
})
};
}])
center.tpl.html:
<aside id="first-item" ng-controller="FirstController as firstController">
<first-directive>
</aside>
<aside id="second-item" ng-controller="SecondController as secondController">
<second-directive>
</aside>
This is the controller to which I would like to get the resolved data.
FirstController.js:
app.controller('FirstController', ['$scope', 'data', function($scope, data){
this.myData = data;
}]);
I got the next error: Unknown provider: dataProvider < - data. Why?
since promise is never resolved before returning. try this one.
app.service("Service", ['$rootscope', '$http', function($rootscope, $http){
var promise;
this.init = function(){
return this.loadData();
};
this.loadData = function(){
var url = "users/getData/json.json";
return $http.get(url).then(function(response){
return response.data;
}, function(error){
alert(error);
})
};
}])
From the ui-router docs:
// The controller waits for every one of the above items to be
// completely resolved before instantiation. For example, the
// controller will not instantiate until promiseObj's promise has
// been resolved. Then those objects are injected into the controller
// and available for use.
It is cleared that the resolved variables will only be available in the controllers defined in the state config. You can not resolve those variables in a normal controller and you are trying to use data from your state config in your controller and hence you are getting that error.
But, to get those data in your FirstController, you can do like this:
app.config('$stateProvider', ['$rootScope', function ($stateProvider) {
$stateProvide.state('State1', {
url: '/State1',
resolve: {
data: function (Service) {
var data = Service.init();
$rootScope.$broadcast("dataReceivedFoo", {data: data});
return data;
}
},
views: {
"header": {
templateUrl: 'views/header.tpl.html'
},
"center": {
templateUrl: 'views/center.tpl.html'
},
"footer": {
templateUrl: 'views/footer.tpl.html'
}
}
})
}]);
And, then read in your controller:
app.controller('FirstController', ['$scope' function($scope){
$scope.$on("dataReceivedFoo", function(response) {
$scope.myData = response.data;
})
}]);
Basically, we are broadcasting the data from your state configuration and then receiving in your FirstController.
I think adding controller: 'FirstController' line to state will solve the problem.
app.config(['$stateProvider', function($stateProvider){
$stateProvide.state('State1', {
url:'/State1',
controller: 'FirstController',
resolve: {
data: function(Service){
return Service.init();
}
},
views: {
"header": {
templateUrl: 'views/header.tpl.html'
},
"center":{
templateUrl: 'views/center.tpl.html'
},
"footer": {
templateUrl: 'views/footer.tpl.html'
}
}
}
})
}
]);
Resolve
You can use resolve to provide your controller with content or data
that is custom to the state. resolve is an optional map of
dependencies which should be injected into the controller.
If any of these dependencies are promises, they will be resolved and
converted to a value before the controller is instantiated and the
$stateChangeSuccess event is fired.
The resolve property is a map object. The map object contains
key/value pairs of:
key – {string}: a name of a dependency to be injected into the
controller.
factory - {string|function}: If string, then it is an
alias for a service. Otherwise if function, then it is injected and
the return value is treated as the dependency. If the result is a
promise, it is resolved before the controller is instantiated and its
value is injected into the controller.
https://github.com/angular-ui/ui-router/wiki
I'm starting to learn AngularJS and so far so good but I am currently stuck on a small issue about an synchronous function.
I would like the function AuthenticationSharedService.login() to be called and returned before executing the rest of the code. How can I do that?
app.js
myApp.config(['$routeProvider', '$httpProvider', 'USER_ROLES',
function ($routeProvider, $httpProvider, USER_ROLES) {
$routeProvider
.when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginController',
access: {
authorizedRoles: [USER_ROLES.all]
}
})
.when('/error', {
templateUrl: 'views/error.html',
access: {
authorizedRoles: [USER_ROLES.all]
}
})
.otherwise({
templateUrl: 'views/main.html',
controller: 'MainController',
access: {
authorizedRoles: [USER_ROLES.user]
}
});
}])
.run(['$rootScope', '$location', 'AuthenticationSharedService', 'Session', 'USER_ROLES',
function($rootScope, $location, AuthenticationSharedService, Session, USER_ROLES) {
$rootScope.$on('$routeChangeStart', function (event, next) {
<!-- Bit of code to execute before going further -->
if (!Session.login) {
console.log('First attempt to login');
AuthenticationSharedService.login();
}
<!-- /////////////////////////////////////////// -->
if (AuthenticationSharedService.isAuthenticated()) {
// user is not allowed
$rootScope.$broadcast("event:auth-notAuthorized");
} else {
// user is not logged in
$rootScope.$broadcast("event:auth-loginRequired");
}
});
}]);
authenticationSharedService.js
myApp.factory('AuthenticationSharedService', ['$rootScope', '$http', '$cookieStore', 'authService', 'Session', 'Account',
function ($rootScope, $http, $cookieStore, authService, Session, Account) {
return {
login: function () {
return Account.get(function(data) {
Session.create(data.login, data.roles);
authService.loginConfirmed(data);
});
}
};
}]);
You need to use resolve. See http://docs.angularjs.org/api/ngRoute/provider/$routeProvider or http://www.bfcamara.com/post/66001429506/authentication-in-a-spa-with-angular - this second link is quite good.
Resolve is a map of dependencies that should be injected into the controller. If any of the mapped objects are functions, the functions will be evaluated and their return values injected. If a function returns a promises, the view will not be rendered until the promise is resolved.
Just FYI, the view will not be rendered at all if the promise is rejected. You would want to deal with that situation in $rootScope.$on('routeChangeError', functionToHandleRejection)
Here's an example that should work for you:
.when('someUrl', {
resolve: {
object: function(AuthenticationSharedService) {
return AuthenticationSharedService.login();
}
}
})
I'm running into the issue, that I have the same resolve function in parent & child states - and depending on the child state, i would like to have it return a different value.
Somehow, instead of overwriting the implementation for it, it simply just takes the behavior from the parent state.
.state('wines', {
url: '/wines',
templateUrl: 'partials/products/index',
controller: 'cwProductsController',
resolve: {
merchandiseView: function() {
return "featured";
}
}
}).state('wines.featured', {
url: "/featured",
templateUrl: 'partials/products/index',
controller: 'cwProductsController',
resolve: {
merchandiseView: function() {
return "featured";
}
}
}).state('wines.curatorsChoice', {
url: "/curators-choice",
templateUrl: 'partials/products/index',
controller: 'cwProductsController',
resolve: {
merchandiseView: function() {
return "curators-choice";
}
}
}).state('wines.stillAvailable', {
url: "/still-available",
templateUrl: 'partials/products/index',
controller: 'cwProductsController',
resolve: {
merchandiseView: function() {
return "still-available";
}
}
});
Here, it always keeps on returning "featured", even when visiting wines/still-available, where I expect merchandiseView to be "still-available".
This is my controller:
angular.module('clubwApp').controller('cwProductsController', [
'$scope', 'cwProduct', '$stateParams', 'merchandiseView', function($scope, cwProduct, $stateParams, merchandiseView) {
console.log(merchandiseView);
$scope.wines = cwProduct.available();
return $scope.merchandiseView = angular.copy(merchandiseView);
}
]);
Is there a way, how i can overwrite this?
Attach you specific data to the data state property instead of the resolve.
At controller initialization time read $state.current.data from the $state injectable.
This is apparently an issue (up until 0.2.15).
Here is a hacky solution to the problem:
http://plnkr.co/edit/j1wCThlv1uczlX7d5cdg?p=preview
the resolve: {test: {this.data.someObject}}
I have 2 routes that share a controller, one needs data resolved prior to the view loading, and the other does not need the resolved data.
Routing segment example:
...
when('/users', {
controller: 'UsersCtrl',
templateUrl: '/partials/users/view.html',
resolve: {
resolvedData : ['Accounts', function(Accounts) {
return Accounts.get();
}]
}
}).
when('/users/add', {
controller: 'UsersCtrl',
templateUrl: '/partials/users/add.html'
})
...
Controller example:
app.controller('UsersCtrl', ['$scope', 'Helper', 'resolvedData',
function($scope, Helper, resolvedData) {
// this works for the first route, but fails for the second route with
// unknown "resolvedDataProvider"
console.log(resolvedData);
}]);
Is there any way I can get the resolvedData in the controller without explicitly using the resolve name as a dependency? So a check can be performed?
Using the $injector does not work. I would like to do something similar to:
if ($injector.has('resolveData')) {
var resolveData = $injector.get('resolveData');
}
However this does not work even for the route that has the resolveData set ('/users'):
app.controller('UsersCtrl', ['$scope', 'Helper', '$injector',
function($scope, Helper, $injector) {
// this does not work -> fails with the unknown "resolvedDataProvider" as well
$injector.get('resolvedData');
}]);
Can this be done in angularjs? Or should I just create a new controller?
Thank you.
Looks like I figured out another way to go. The resolved data is part of the $route. So you can access it using:
app.controller('UsersCtrl', ['$scope', '$route', 'Helper',
function($scope, $route, Helper) {
if ($route.current.locals.resolvedData) {
var resolvedData = $route.current.locals.resolvedData;
}
}]);
If the other route doesn't need it, just inject undefined on that route:
router:
when('/users', {
controller: 'UsersCtrl',
templateUrl: '/partials/users/view.html',
resolve: {
resolvedData : ['Accounts', function(Accounts) {
return Accounts.get();
}]
}
}).
when('/users/add', {
controller: 'UsersCtrl',
templateUrl: '/partials/users/add.html',
resolve: {
resolvedData: function() {
return undefined;
}
}
})
controller:
app.controller('UsersCtrl', ['$scope', 'Helper', 'resolvedData',
function($scope, Helper, resolvedData) {
if(resolvedData){
//set some scope stuff for it
} else {
//do what you do when there is no resolvedData
}
}]);