In my main module i have used ui-bootstrap modal for checking login authentication.From run block i have called to loginModal service but it is giving Error
TypeError: loginModal is not a function
angular.module('myApp', ['ui.router', 'ui.bootstrap', 'loginServices','leaveServices']). config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider.
state('home', {
url:'/home',
data: {
requireLogin: false
},
views: {
'': {
templateUrl: 'partials/templates/assets/home.html'
}
}
}).
state('home.about', {
url: '/about',
templateUrl: 'partials/templates/assets/about.html'
}).
state('home.contact', {
url: '/contact',
templateUrl: 'partials/templates/assets/contactUs.html'
}).
state('/login', {
url: '/login',
data: {
requireLogin: false
},
templateUrl: 'partials/login.html',
controller: loginUserController
}).
state('/register', {
url:'/register',
data: {
requireLogin: false
},
templateUrl: 'partials/registerUser.html',
controller: registerController
}).
state('/getAllUsers', {
url: '/getAllUsers',
data: {
requireLogin: false
},
templateUrl: 'partials/getAllUsers.html',
controller: getUsersController
}).
state('/updateUser', {
url : '/updateUser/:id/:name',
data: {
requireLogin: true
},
params: {'id':null, 'name':null},
templateUrl: 'partials/updateUser.html',
controller: updateUserController
}).
state('/userLeave', {
url : '/userLeave:name',
data: {
requireLogin: true
},
params: {'name': null},
templateUrl: 'partials/userLeave.html',
controller: userLeaveController
}).
state('/leaveRequest', {
url : '/leaveRequest',
data: {
requireLogin: true
},
templateUrl: 'partials/leaveRequest.html'
});
}])
.run(function ($rootScope, $state, loginModal) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
var requireLogin = toState.data.requireLogin;
console.log('going to state '+toState.name);
if (requireLogin && typeof $rootScope.currentUser === 'undefined') {
event.preventDefault();
loginModal().then(function () {
return $state.go(toState.name, toParams);
})
.catch(function () {
return $state.go('/login');
});
}
});
})
.factory('loginModal', function ($modal, $rootScope) {
function assignCurrentUser (user) {
$rootScope.currentUser = user;
return user;
}
return function() {
var instance = $modal.open({
templateUrl: 'partials/login.html',
controller: loginUserController
});
return instance.result.then(assignCurrentUser);
}
});
here login controller
loginUserController.$inject = ['$scope','$http', 'loginFactory', '$location', '$state'];
function loginUserController($scope,$http,loginFactory,$location, $state){
$scope.validateLogin = function(name,password){
$http.get("http://localhost:3010/validateLogin?userName="+name+"&password="+password)
.then(function(response) {
if(response.data.length != 0) {
console.log("logged user data is "+JSON.stringify(response.data));
$state.transitionTo('/userLeave', {name: name});
// $scope.$close(response);
}
else
$scope.inValidUser = 'Invalid User';
});
};
$scope.cancel = $scope.$dismiss;
}
Could be because you're using an Angular service which expects a constructor which in turn, should not be returning something.
Try changing to a factory, eg
.factory('loginModal', ...
Related
I am trying to restrict access to some pages within the public directory using Angular routing.
.when('/adminprofile', {
templateUrl: '../partials/adminprofile.html',
access: {restricted: true}
})
I am trying to read what I believe is a property called access which I declared, called access
myApp.run(function ($rootScope, $location, $route, AuthService) {
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.access.restricted && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
});
But what I get is this error:
TypeError: next.access is undefined
How can I read the property or how can i achieve this in a better way?, Thanks
EDIT :
According to suggestion, I have changed the code and it looks as it follows:
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: '../partials/home.html',
resolve: {
access: false
}
})
.when('/home', {
templateUrl: '../partials/home.html',
resolve: {
access: false
}
})
.when('/login', {
templateUrl: '../partials/login.html',
controller: 'loginController',
resolve: {
access: false
}
})
.when('/logout', {
controller: 'logoutController',
resolve: {
access: false
}
})
.when('/register', {
templateUrl: '../partials/register.html',
controller: 'registerController',
resolve: {
access: false
}
})
.when('/adminprofile', {
templateUrl: '../partials/adminprofile.html',
resolve: {
access: true
}
})
.otherwise({
redirectTo: '/'
});
});
And I have my run function:
myApp.run(function ($rootScope, $location, $route, AuthService) {
debugger;
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.resolve.access && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
} else{
$location.path($route.current.originalPath);
}
});
});
});
Now I can see the value of access:
next.resolve.access
but is not displaying anything, I run in debug and can see that actually is going through the $routeChangeStart callback , whyyyyy?? helppppp!
ok fellas, is done, this is the right way to do it:
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: '../partials/home.html',
resolve: {
access: function() {
return false;
}
}
})
.when('/home', {
templateUrl: '../partials/home.html',
resolve: {
access: function() {
return false;
}
}
})
.when('/login', {
templateUrl: '../partials/login.html',
controller: 'loginController',
resolve: {
access: function() {
return false;
}
}
})
.when('/logout', {
controller: 'logoutController',
resolve: {
access: function() {
return false;
}
}
})
.when('/register', {
templateUrl: '../partials/register.html',
controller: 'registerController',
resolve: {
access: function() {
return false;
}
}
})
.when('/adminprofile', {
templateUrl: '../partials/adminprofile.html',
resolve: {
access: function() {
return true;
}
}
})
.otherwise({
redirectTo: '/'
});
});
myApp.run(function ($rootScope, $location, $route, AuthService) {
debugger;
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.resolve.access && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
});
resolve has to be a function
Resolve will open your route with a resolved variable (that can be injected into controller) as soon as it gets value (instantly or when returned promise will be resolved)
as it was not returning a value, the router seems to be stuck waiting for a value to resolve.
I have the following routing:
$stateProvider
.state('message', {
parent: 'admin',
url: '/message',
templateUrl: './app/gol88/admin/messaging/page/list.page.html',
controller: 'ListController as listCtrl'
})
.state('replyMessage', {
parent: 'message',
url: '/{ticketId:int}/reply', //this should have {id} as stateParams
onEnter: ['$mdDialog', '$state', function($mdDialog, $state) {
$mdDialog.show({
controller: ReplyController,
controllerAs: 'replyCtrl',
templateUrl: '/app/gol88/admin/messaging/page/dialog/reply.html',
parent: angular.element(document.body),
clickOutsideToClose:true
}).then(function(response) {
}, function() {
$state.go('message');
});
}],
onExit: ['$mdDialog', function($mdDialog) {
$mdDialog.hide();
}]
})
;
When I tried to navigate to replyMessage state for the first time and use the $stateParams.ticketId in my Controller I am getting the value. However, when I transitioned to message state , and try to transition to replyMessage state back again, the $stateParams.ticketId is now undefined. Why is that so?
This is my controller for replyMessage state:
var ReplyForm = require('../model/reply_form.model');
ReplyController.$inject = ['$stateParams', 'TicketApiService'];
function ReplyController($stateParams, TicketApiService) {
var vm = this;
vm.ticket = null;
vm.ReplyForm = ReplyForm;
vm.addComment = addComment;
init();
function init() {
console.log($stateParams.ticketId);
/* TicketApiService.details($stateParams.ticketId)
.then(function(response) {
vm.ticket = response;
})
;*/
}
function addComment() {
TicketApiService.addComment($stateParams.ticketId, vm.ReplyForm.toPayload())
.then(function(response) {s.
vm.ticket.comments.unshift(response);
vm.ReplyForm.reset();
})
;
}
}
module.exports = ReplyController;
in my web app am using angular-ui-router for state change. Below is my route.config file.
route-config.js
$stateProvider
.state('login', {
url: '/',
views:{
pageContent:{
templateUrl: 'Login/login_default.html',
controller: 'loginController'
},
footer:{
templateUrl: 'common/footer.html',
controller: 'footerController'
}
},onEnter: function(){
// if(true){ $state.go('dashboard')}
},resolve:{
dependencies:['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load(['ui.bootstrap','ngMessages','headerCtrl','footerCtrl']);
}],
loginController:['$q', '$ocLazyLoad','dependencies',function($q, $ocLazyLoad,dependencies) {
var deferred = $q.defer();
require.ensure(['./styles/login/login.less'], function (require) {
var mod = require('./Login');
$ocLazyLoad.load({
name: mod.name,
});
deferred.resolve(mod.controller);
});
return deferred.promise;
}]
},public:true
})
.state('Password', {
url: '/Password?token',
views:{
header:{
templateUrl: 'common/header.html',
controller:"headerController"
},
pageContent:{
templateUrl: 'ForgotPassword/forgotPassword.html',
controller: 'forgotPasswordCtrl'
},
footer:{
templateUrl: 'common/innerFooter.html',
controller: 'footerController'
}
},
resolve:{
dependencies:['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load(['headerCtrl','ui.bootstrap']);
}],
forgotPasswordCtrl:['$q','$ocLazyLoad','dependencies', function($q,$ocLazyLoad,dependencies) {
var deferred = $q.defer();
require.ensure(['./styles/forgotPassword/forgotPassword.less'], function (require) {
var mod = require('./ForgotPassword');
$ocLazyLoad.load({
name: mod.name,
});
deferred.resolve(mod.controller);
});
return deferred.promise;
}]
},public:true
});
In index.js file am checking the $stateChange as below.
run(function($http,$rootScope,$cookieStore,$location,$window,$state) {
$rootScope.token = $http.defaults.headers.common['SessionID'];
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
let loggedIn = $cookieStore.get('success');
if(!toState.public && !loggedIn){
$state.go('login');
event.preventDefault();
}
});
});
And below is the Html page on which on click on password button it should go to forgot password page or if i will type password on the URL it should go to the password page.
<div class="inp-wrapper frgtpwd">
<a style="text-decoration:none;color:#000;" ui-sref="Password" class="password">FORGOT PASSWORD ?</a>
</div>
I tried everything but unable to fix this issue. If i will check the toState.name in $statechangeStart function and try to go to the password page then it is going under a continuous loop and throwing error like Maximum call stack(something like this).
I'm working on authentication with angularjs, so after connecting my user I want to redirect him to the home page:
$scope.submit = function(user) {
var request = {
method: 'POST',
url: 'http://localhost:9001/signIn',
headers: {
'Content-Type': 'application/json'
},
data: {
"email": user.email,
"password": user.password,
"rememberMe": true
}
};
$http(request).then(function(data) {
$location.path('/home');
}, function(error) {
console.log(error);
});
};
here is my configuration:
app.config(function($urlRouterProvider, $stateProvider, $httpProvider, $authProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home',
controller: 'HomeCtrl',
resolve: {
authenticated: function($q, $location, $auth) {
var deferred = $q.defer();
if (!$auth.isAuthenticated()) {
$location.path('/signIn');
} else {
deferred.resolve();
}
return deferred.promise;
}
}
})
.state('signIn', {
url: '/signIn',
templateUrl: '/signIn',
controller: 'SignInCtrl'
});
});
I tried this:
$http(request).then(function(data) {
$scope.$evalAsync(function() {
$location.path('/home');
});
console.log(data);
}, function(error) {
console.log(error);
});
also :
$location.path('/home');
$location.replace();
Neither of the above work, any help is greatly appreciated.
The home state resolver function fails to resolve or reject the $q.defer promise when $auth.isAuthenticated() returns false. This will cause the promise to hang and create a memory leak.
//ERRONEOUS CODE
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home',
controller: 'HomeCtrl',
resolve: {
authenticated: function($q, $location, $auth) {
var deferred = $q.defer();
if (!$auth.isAuthenticated()) {
$location.path('/signIn');
//FAILS to resolve or reject promise
} else {
deferred.resolve();
}
return deferred.promise;
}
}
})
Instead return a rejection when not authenticated:
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home',
controller: 'HomeCtrl',
resolve: {
authenticated: function($q, $location, $auth) {
//var deferred = $q.defer();
if ($auth.isAuthenticated()) {
return $q.resolve("AUTHENTICATED");
};
//otherwise
return $q.reject("NOT AUTHENTICATED");
})
}
})
When a resolver function returns a rejected promise, the state change will be prevented and the $stateChangeError event will be broadcast on $rootScope.
I have tried several method but $state.go() is not refreshing my page.Here is my controller. All process works but i cannot reload the browse page using $state.go() function.
angular.module('kawaadi.controllers', [])
.controller('AppCtrl', function ($scope, Service, $ionicLoading, $ionicModal, $ionicPopup, $timeout, $state, $http,$location) {
$scope.loginData = {};
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function (modal) {
$scope.modal = modal;
});
$scope.closeLogin = function () {
$scope.modal.hide();
};
$scope.login = function () {
$scope.modal.show();
};
$scope.logout = function () {
localStorage.setItem("token", "");
$state.go('login');
};
$scope.statusData = function (pid, uid, status) {
$ionicLoading.show({
template: 'Processing...'
});
Service.change_status(pid, uid, status, $http).success(function (data) {
if (data.status === 'success' && data.notification_status === 'success') {
$ionicLoading.hide();
var alertPopup = $ionicPopup.alert({
title: 'Success!',
template: 'Successfully changed and notification has been send!'
});
} else if (data.status === 'success' && data.notification_status === 'failure') {
$ionicLoading.hide();
var alertPopup = $ionicPopup.alert({
title: 'Success!',
template: 'Successfully changed but failed to send notification!!'
});
}
alertPopup.then(function (res) {
if (res == true) {
$state.go('app.browse');
}
});
}).error(function (data) {
var alertPopup = $ionicPopup.alert({
title: 'Process failed!',
template: 'Some thing went wrong!'
});
});
}
})
and here is my url router
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'templates/auth.html',
controller: 'LoginCtrl'
})
.state('app', {
url: '/app',
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.search', {
url: '/search',
views: {
'menuContent': {
templateUrl: 'templates/search.html'
}
}
})
.state('app.browse', {
url: '/browse',
views: {
'menuContent': {
templateUrl: 'templates/browse.html',
controller: 'pickupCtrl'
}
}
})
.state('app.playlists', {
url: '/playlists',
views: {
'menuContent': {
templateUrl: 'templates/playlists.html',
controller: 'PlaylistsCtrl'
}
}
})
.state('app.single', {
url: '/playlists/:playlistId',
views: {
'menuContent': {
templateUrl: 'templates/playlist.html',
controller: 'PlaylistCtrl'
}
}
});
});
Please guide me. Thanks in advance
Please modify all your states as
.state('emailConfirmation',{
cache: false,
url:"/emailConfirmation",
templateUrl:"app/session/emailConfirmation.html",
controller: 'EmailConfirmationCtrl'
})
and to reload the current page please use these command
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
If you want to force reload the current state, then you probably need to use $state.go($state.current.name, $state.params, {reload: true}) as mentioned here
Just Add the following in Your ion-view tag
<ion-view cache-view="false">