Unable to access a public state in angular project? - angularjs

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).

Related

Angular distribution app not working as spected

I have developed an application with angular, but when I build the distribution application with grunt I have an strange behaviour of my application.
For example:
console.log("START");
AuthService.refresh(LoopBackAuth.accessTokenId).then(function() {
console.log("USER LOADED");
$state.go('main.documents');
});
and in main.documents I have:
console.log("DOCUMENTS");
so the flow should be (the flow that I have in my production files):
log-->START
log-->USER LOADED
log-->DOCUMENTS
but the flow that I get in the production files is the following:
log-->START
log-->DOCUMENTS
log-->USER LOADED
and in my documents view my $rootScope where I save my user details it is empty and it fails all the time.
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider.state('login', {
url: '/login',
templateUrl: 'views/login.html',
controller: 'LoginCtrl',
authenticate: false
});
$stateProvider.state('main', {
abstract: true,
url: '/',
templateUrl: 'views/main.html',
controller: 'MainCtrl',
authenticate: true
});
$stateProvider.state('main.documents', {
url: 'documents',
templateUrl: 'views/main/documents.html',
controller: 'MainDocumentsCtrl',
authenticate: true
});
$stateProvider.state('main.information', {
url: 'information',
templateUrl: 'views/main/managing-information.html',
controller: 'MainInformationCtrl',
authenticate: true
});
$stateProvider.state('main.calendar', {
url: 'calendar',
templateUrl: 'views/main/calendar.html',
controller: 'MainCalendarCtrl',
authenticate: true
});
$stateProvider.state('main.notices', {
url: 'notices',
templateUrl: 'views/main/notices.html',
controller: 'MainNoticesCtrl',
authenticate: true
});
$stateProvider.state('main.settings', {
url: 'settings',
templateUrl: 'views/main/settings.html',
controller: 'MainSettingsCtrl',
authenticate: true
});
$urlRouterProvider.otherwise('login');
}])
User authentication:
.run(['$rootScope', '$state', 'LoopBackAuth', 'Authentication', function($rootScope, $state, LoopBackAuth, AuthService) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
// redirect to login page if not logged in
if (toState.authenticate && !LoopBackAuth.accessTokenId) {
event.preventDefault();
$rootScope.returnTo = {
state: toState,
params: toParams
};
$state.go('login');
}
});
// Get data from localstorage after pagerefresh
// and load user data into rootscope.
if (LoopBackAuth.accessTokenId && !$rootScope.currentUser) {
console.log("USER LOGGED IN");
AuthService.refresh(LoopBackAuth.accessTokenId).then(function() {
console.log("USER LOADED");
$state.go('main.documents');
});
}
}]);

$state.go is not working when project is run with ionic serve --lab command

Hello I am working with ionic framework and I want to redirect to another page
after successfully login .When I run project using command:
ionic serve then $state.go working properly but when I run project using
ionic serve --lab it is not working
.controller('AppCtrl', function($scope,$http, $ionicModal,$location,$state, $timeout) {
// Form data for the login modal
$scope.loginData = {};
// Create the login modal that we will use later
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
// Triggered in the login modal to close it
$scope.closeLogin = function() {
$scope.modal.hide();
};
// Open the login modal
$scope.login = function() {
$scope.modal.show();
};
// Perform the login action when the user submits the login form
$scope.doLogin = function() {
alert($scope.loginData.username);
alert($scope.loginData.password);
$http({
method: 'POST',
url: 'http://localhost/home_owner12/admin/api/login',
data: {username:$scope.loginData.username,password:$scope.loginData.password},
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}
})
.then(function successCallback(response)
{
if(response.data.length > 0)
{
$state.go('app.search');
console.log('the state is '+$state.current);
}
else
{
alert("Invalid email or pasword");
///$location.path('/search');
}
}, function errorCallback(response)
{
alert("Invalid email pasword");
});
};
})
here is state:
config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.search', {
url: '/search',
views: {
'menuContent': {
templateUrl: 'templates/search.html',
controller: 'AppCtrl'
}
}
});
and module
angular.module('starter', ['ionic', 'starter.controllers', 'ui.router'])
The app.search page's controller goes to AppCtrl in place.
Because AppCtrl runs a second time, it is entering an infinite loop.
Replace the code with that
config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.search', {
url: '/search',
views: {
'menuContent': {
templateUrl: 'templates/search.html',
controller: 'SearchCtrl'
}
}
});
and
.controller('SearchCtrl', function($scope,$http, $ionicModal,$location,$state, $timeout) {
............
.........
.......
})

error while calling to $modal service from run block

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', ...

$state.go() is not refreshing my ionic page

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">

Authenticated user doesn't get updated in AngularFire

I'm using the AngularFire example for ui-router.
// for ui-router
app.run(["$rootScope", "$state", function($rootScope, $state) {
$rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
if (error === "AUTH_REQUIRED") {
$state.go("home");
}
});
}]);
app.config(["$stateProvider", function ($stateProvider) {
$stateProvider
.state("home", {
controller: "HomeCtrl",
templateUrl: "views/home.html",
resolve: {
"currentAuth": ["Auth", function(Auth) {
return Auth.$waitForAuth();
}]
}
})
.state("account", {
controller: "AccountCtrl",
templateUrl: "views/account.html",
resolve: {
"currentAuth": ["Auth", function(Auth) {
return Auth.$requireAuth();
}]
}
});
}]);
app.controller("HomeCtrl", ["currentAuth", function(currentAuth) {
}]);
app.controller("AccountCtrl", ["currentAuth", function(currentAuth) {
}]);
Everything works for the first user. The problem is that when the first user logs out and the second one logs in, the "currentAuth" still holds the first user's information. Why doesn't it get updated with the new login?
It actually gets updated if I refresh the page, but how can I load the new data without refreshing?

Resources