I want to show UI after all promises has complete.
When I move to any step , before this I do some code execution.
I am stuck here my templateURl gets executed synchronously. I want templateUrl should execute once all execution has been completed (from .run method).
below is my app.js
(function () {
"use strict";
var app = angular.module("autoQuote", ["ui.router", "ngResource"]);
app.config(["$stateProvider", "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state("Cars", {
url: "",
templateUrl: "/rc1/renderStep/cars"
})
.state("Drivers", {
url: "/drivers",
templateUrl: "/rc1/renderStep/drivers",
controller: "renderStepCtrl",
})
}])
app.run(["$log", "$rootScope", "$state", "dtoResource", "questionResource", "postDtoFactory", function ($log, $rootScope, $state, dtoResource, questionResource, postDtoFactory) {
$log.info('Post DTO on page load.');
$rootScope.$state = $state;
dtoResource.rc1LoadDTO()
.then(function (data) {
$rootScope.AutoQuote = data;
postDtoFactory.postDto()
.then(function (data) {
questionResource.getQuestions($rootScope.AutoQuote.postAutoQuoteObj.SessionInfo.StateCode)
.then(function (questions) {
console.log('questions', questions);
$rootScope.questions = questions;
//$rootScope.answers = {PC:12345,VehicleYear_1:2017}; // test code
console.log('Obtained questions. Assigned to rootscope');
})
})
})
.then(function () {
console.log('This should be printed after the above methods are done executing');
console.log($rootScope);
})
}])
}());
you can put the code to ui-router resolve.
$stateProvider.state('demo', {
url: '/demo',
template: require('./views/demo.html'),
controller: 'DemoController as vm',
resolve: {
resolvedInfo: [demoService,
function (demoService) {
//put some code execution
return promise;
}]
}
})
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 want to remove exclamation marks from url state routing like my url is now http://localhost:3000/#!/auth/register
i just want to remove this "!" marks from url after "#"
Is it possible to do? with mean.io
here is my app.js/system.js
'use strict';
//Setting up route
angular.module('mean').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// For unmatched routes:
//$urlRouterProvider.otherwise('/');
var checkLoggedin = function($q, $timeout, $http, $location) {
// Initialize a new promise
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('/loggedin').success(function(user) {
// Authenticated
if (user !== '0') $timeout(deferred.resolve);
// Not Authenticated
else {
$timeout(deferred.reject);
$location.url('/auth/login');
}
});
return deferred.promise;
};
// console.log($stateProvider);
// states for my app
$stateProvider
.state('tasks', {
url: '/kanban/:projectId/:projectSlug',
templateUrl: 'system/views/index.html',
controller: 'IndexController',
resolve: {
loggedin: checkLoggedin,
onEnter: function($stateParams,$state, $uibModal) {
if ( $stateParams.projectId != "" ) {
updateTopMenu('Kanban','task','#!/kanban/'+$stateParams.projectId+'/'+$stateParams.projectSlug);
updateTopMenu('Schedule','schedule','#!/schedule');
}
}
}
}).state('home',{
url:'/',
templateUrl: 'projects/views/index.html',
controller: 'ProjectController',
resolve:{
loggedin: checkLoggedin
}
}).state('taskEdit',{
url:'/kanban/:projectId/:projectSlug/:taskSlug',
templateUrl: 'system/views/index.html',
controller: 'IndexController',
resolve:{
loggedin: checkLoggedin
}
}).state('taskAdd',{
url: "/task/taskAdd",
onEnter: function($stateParams, $state, $uibModal) {
$uibModal.open({
templateUrl: "system/views/include/model.html",
resolve: {},
controller: function($scope, $state, itemService) {
/*
$scope.state = $state.current;
$scope.params = $stateParams;
$scope.item = itemService.get($stateParams.id);
*/
$scope.ok = function () {
$scope.$close('clicked ok');
};
$scope.dismiss = function () {
$scope.$dismiss('clicked cancel');
};
}
}).result.then(function (result) {
// $scope.$close
alert('result ->' + result);
}, function (result) {
// $scope.$dismiss
return $state.transitionTo("home");
alert('dismiss ->' + result);
}).finally(function () {
// handle finally
return $state.transitionTo("tasks");
});
}
});
}
]).config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('!');
}
]);
you have configured it here
function($locationProvider) {
$locationProvider.hashPrefix('!');
}
remove this line to get ! removed from url
or enable html5mode using below code to remove # from url
$locationProvider.html5Mode(true);
but please read more about how url routes are handled in angular, and server side routing vs client side routing etc, before enabling html5mode
Change $locationProvider.hashPrefix('!'); to $locationProvider.hashPrefix('');
System.js
.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('');
}
]);
I'm trying to update my nav bar every time the route changes, and I've tried this, however it doesn't seem to be working. It's supposed to write bob every time the view changes, but it only writes it when the controller loads.
nav.controller.js
angular.module('app')
.controller('navController', ['$scope', '$state', function ($scope, $state) {
var timeSpan;
$scope.user;
...
// Update when the view changes.
$scope.reload = function () {
$state.reload();
};
$scope.$state = $state;
$scope.$watch('$state.$current.locals.globals.view', function () {
console.log('bob');
$scope.user = userService.get();
});
...
$scope.reroute = function(route){
$state.go(route);
};
}]);
route.js
angular.module('SimPlannerApp')
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when('/','/signin');
$stateProvider
.state('signin', {
url: "/signin",
templateUrl: 'views/signin.html',
controller: 'signinController'
})
.state('menu', {
url: "/menu",
templateUrl: 'views/menu.html',
controller: 'menuController',
resolve: {
config: function (configService) {
return configService.getConfig()
.then(function(response){
return response.data;
})
.catch(function(error){
console.log('Error : ', error);
return undefined;
});
}
}
})
.state('view', {
url: '/view/:view',
templateUrl: 'views/view.html',
controller: 'viewController',
resolve: {
view: function ($stateParams, configService) {
return configService.getConfig()
.then(function(response){
var config = response.data;
for (var i = 0; i < config.views.length; i++) {
if (config.views[i].route === $stateParams.view) {
return config.views[i];
}
}
return undefined;
})
.catch(function(error){
console.log('Error : ', error);
return undefined;
});
},
config: function (configService) {
return configService.getConfig()
.then(function(response){
return response.data;
})
.catch(function(error){
console.log('Error : ', error);
return undefined;
});
}
}
})
.state('404', {
url: '{path:.*}',
templateUrl: 'views/404.html',
controller: 'errorController'
});
});
PS:
Propably should mention I'm using AngularJS with ui-router.
Not sure if I fully understand but would it not be better to use $stateChangeSuccess to detect when the route changes? I use this in the .run block
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams){ ... })
but you could place this in your Controller
https://github.com/angular-ui/ui-router/wiki
You can handle with $locationChangeStart like below:
$rootScope.$on('$locationChangeStart', function () {
console.log('bob');
});
You should write this in .module.run() function.
angular
.module()
.run(function($rootScope) {
// to Here
})
I am trying to create some routing that will resolve calls to my rest api
before the page loads. Because I can't inject a service created using
app.factory(), I am attempting to create a provider to do this so I can use it in my config routing, but I'm
getting Error: [$injector:unpr] Unknown provider: $http
I want to be able to call the provider in mainFlow.api for 4 or five endpoints
that will resolve before the page loads. Am I going about this the correct way?
My code:
service.js
var mainApp = angular.module('mainApp');
mainApp.provider('choiceService', ['$http', function($http) {
return {
$get: function() {
return {
get: function(url) {
return $http.get(url);
}
};
}
};
}]);
config.js
var mainApp = angular.module('mainApp', [
'ui.router'
]);
mainApp.config(['$stateProvider', '$urlRouterProvider', '$choiceServiceProvider',
function($stateProvider, $urlRouterProvider, choiceServiceProvider) {
$stateProvider
.state('mainFlow', {
abstract: true,
url: '/base',
template: '<ui-view/>'
})
.state('mainFlow.choose-main', {
url: '',
templateUrl: '/choose_main.html',
})
.state('mainFlow.contact', {
controller: 'ContactFormController',
url: '/contact-details',
templateUrl: '/panel_contact_info.html',
})
.state('mainFlow.api', {
url: '/about-your-api',
controller: 'ApiFormController',
templateUrl: '/panel_about_your_api.html',
resolve: {
choice: function(choiceServiceProvider) {
return choiceServiceProvider.get('/api/yes-no-choice/');
},
other_choice: function(choiceServiceProvider){
return choiceServiceProvider.get('/api/my-other-choice/')
}
}
})
Then I can use the resolved data in controller.js
controller.js
var mainApp = angular.module('mainApp');
mainApp.controller('ApiFormController', [
'$scope',
'$state',
'choiceService',
function($scope, $state, choiceService) {
$scope.choices = choiceService;
}
]);
I was passing $http in service.js when there was no need. I was also passing in '$choiceServiceProvider' in config.js when it should have been just 'choiceServiceProvider'
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();
}
}
})