Angular flickers when authenticating user - javascript

I need help eliminating a flicker with Angular. I am getting a flicker every time a new route is passed through. I have a login and logout button outside the ng-view which uses ng-if="authenticated". The problem is any time a menu item is clicked and a new view is displayed the logout or login button flickers. Is there a way to eliminate this? Below is the module, config and run function.
PS. I am very new to Angular. This was a script from a tutorial on using Angular, php and mysql for a login system.
var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'ui.bootstrap', 'toaster']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/login', {
title: 'Login',
templateUrl: 'views/login.html',
controller: 'authCtrl'
})
.when('/logout', {
title: 'Logout',
templateUrl: 'views/login.html',
controller: 'logoutCtrl'
})
.when('/signup', {
title: 'Signup',
templateUrl: 'views/signup.html',
controller: 'authCtrl'
})
.when('/dashboard', {
title: 'Dashboard',
templateUrl: 'views/dashboard.html',
controller: 'authCtrl'
})
.when('/posts', {
title: 'Posts',
templateUrl: 'views/posts.html',
controller: 'authCtrl'
})
.when('/stats', {
title: 'Stats',
templateUrl: 'views/stats.html',
controller: 'authCtrl'
})
.when('/ambas', {
title: 'Ambassadors',
templateUrl: 'views/ambassadors.html',
controller: 'authCtrl'
})
.when('/images', {
title: 'Images',
templateUrl: 'views/images.html',
controller: 'authCtrl'
})
.when('/', {
title: 'Login',
templateUrl: 'views/login.html',
controller: 'authCtrl'
})
.otherwise({
redirectTo: '/posts'
});
}])
.run(function ($rootScope, $location, Data) {
$rootScope.$on("$routeChangeStart", function (event, next, current) {
$rootScope.authenticated = false;
Data.get('session').then(function (results) {
if (results.uid) {
$rootScope.authenticated = true;
$rootScope.uid = results.uid;
$rootScope.name = results.name;
$rootScope.email = results.email;
} else {
var nextUrl = next.$$route.originalPath;
if (nextUrl == '/signup' || nextUrl == '/login') {
} else {
$location.path("/login");
}
}
});
});
});

You are setting the authenticated value to false on every route change start. So every time a user clicks to change the route you set it to false, and then a few moments later you set it to true if authentication is fine. That will cause a flicker.
So, remove the $rootScope.authenticated = false; from the $routeChangeStart callback.
$rootScope.$on("$routeChangeStart", function (event, next, current) {
//$rootScope.authenticated = false; <--- *remove this*
Data.get('session').then(function (results) {
...........

Related

Unexpected identifier while adding controller to ngRoute

I've faced with such problem, when I add controller to my route code it fails to unexpected identifier. Have no idea why it's happening
This is my routeProvider:
app.config(function($routeProvider) {
$routeProvider
.when("/login", {
title: 'Login',
templateUrl: 'assets/login.html'
controller: authCtrl
})
});
And this is my controller:
app.controller('authCtrl', function ($scope, $rootScope, $routeParams, $location, $http, Data) {
//initially set those objects to null to avoid undefined error
$scope.login = {};
$scope.signup = {};
$scope.doLogin = function (customer) {
Data.post('login', {
customer: customer
}).then(function (results) {
Data.toast(results);
if (results.status == "success") {
$location.path('dashboard');
}
});
};
$scope.signup = {email:'',password:'',name:'',phone:'',address:''};
$scope.signUp = function (customer) {
Data.post('signUp', {
customer: customer
}).then(function (results) {
Data.toast(results);
if (results.status == "success") {
$location.path('dashboard');
}
});
};
$scope.logout = function () {
Data.get('logout').then(function (results) {
Data.toast(results);
$location.path('login');
});
}
});
I've included such paths in my html:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"/>
<script src="app/angular-route.min.js"></script>
<script src="app/angular-animate.min.js" ></script>
<script src="app/toaster.js"></script>
<script src="app/app.js"></script>
There is some typos in your code :
app.config(function($routeProvider) {
$routeProvider
.when("/login", {
title: 'Login',
templateUrl: 'assets/login.html', // <---- missing ','
controller: 'authCtrl' // <----- should be format to string
})
});
Not sure if it will solve your problem
try it.
app.config(function($routeProvider) {
$routeProvider
.when("/login", {
title: 'Login',
templateUrl: 'assets/login.html',
controller: 'authCtrl' // <-- string
})
});
the controller name must pass as a string..try this
app.config(function($routeProvider) {
$routeProvider
.when("/login", {
title: 'Login',
templateUrl: 'assets/login.html',
controller: 'authCtrl'
})
});

angularjs - backspace is not working

I have a problem when i click on backspace
it doesn't go to the last page
i don't know how to fix it sometime it does go the last page only when i go from app.home page to app.newJob.Step1 and press backspace it goes back to home but not always
here is my router
'use strict';
angular.module('ijob').
config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'Views/login.html',
data: {
requireLogin: false
}
})
.state('app', {
abstract: true,
template: '<ui-view/>',
data: {
requireLogin: true
}
})
.state('app.home', {
url: '/home',
templateUrl: '/Views/home.html'
})
.state('app.editJob', {
url: '/editJob',
templateUrl: 'Views/editJob.html'
})
.state('app.purchasePackages', {
url: '/purchasePackages',
templateUrl: 'Views/purchasePackages.html'
})
.state('app.accountDetails', {
url: '/accountDetails',
templateUrl: 'Views/accountDetails.html'
})
.state('app.jobOrder2', {
url: '/jobOrder2',
templateUrl: 'Views/jobOrder2.html'
})
.state('app.newJob', {
abstract: true,
templateUrl: 'Views/newJob/newJob.html',
url: '/newJob'
})
.state('app.newJob.Step1', {
url: '/newJob/step1',
templateUrl: 'Views/newJob/step1.html'
})
.state('app.newJob.Step2', {
url: '/newJob/step2',
templateUrl: 'Views/newJob/step2.html'
})
.state('app.newJob.Step3', {
url: '/newJob/step3',
templateUrl: 'Views/newJob/step3.html'
})
.state('app.newJob.Step4', {
url: '/newJob/step4',
templateUrl: 'Views/newJob/step4.html'
})
.state('app.newJob.Step5', {
url: '/newJob/step5',
templateUrl: 'Views/newJob/step5.html'
});
$urlRouterProvider.otherwise('/home');
// $locationProvider.html5Mode(true);
})
.config(function config() {
});
and my app
'use strict';
// Declare app level module which depends on views, and components
angular.module('ijob', [
'ui.router', 'ngRoute', 'btorfs.multiselect', 'ngCookies', 'ngResource'
]);
var app = angular.module('ijob');
app.run(['$state', '$cookieStore', '$rootScope', 'Auth', 'UserService',
function ($state, $cookieStore, $rootScope, auth, userService) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
var requireLogin = toState.data.requireLogin;
if (requireLogin && !($cookieStore.get('authdata'))) {
event.preventDefault();
$state.go('login');
}
else if ($cookieStore.get('authdata') && $state.current.name !== toState.name) {
userService.token = auth.getCredentials($cookieStore.get('authdata'));
console.log(userService);
$state.current.name = toState.name;
$state.go(toState.name);
}
});
}]);
sometimes i get that error
Error: No such state 'app.newJob.Step1'
or
Error: No such state 'login'
and the states do exist.
its something about the ui router?
or there is anyway to override that?

Possible to dynamically load controllers in Angular

When I go to a specific view in my Angular project, every controller code is being load.
I understand that it's possible to prevent this. But is it possible in the following situation?
App.js config:
app.config(['$stateProvider', '$urlRouterProvider', '$httpProvider',
function($stateProvider, $urlRouterProvider, $httpProvider, $locationProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
$stateProvider.state('home', {
url: "/home",
templateUrl: 'views/Home.html',
controller: "MainController",
onEnter: ['$state', 'auth', function($state, auth) {
if (auth.isLoggedIn()) {
$state.go('challenge');
}
}]
}).state('login', {
url: '/login',
templateUrl: 'views/Login.html',
controller: 'UserCtrl',
onEnter: ['$state', 'auth', function($state, auth) {
if (auth.isLoggedIn()) {
$state.go('home');
} else {
//console.log("Niet ingelogd")
}
}]
}).state('register', {
url: '/register',
templateUrl: 'views/Register.html',
controller: 'UserCtrl',
onEnter: ['$state', 'auth', function($state, auth) {
if (auth.isLoggedIn()) {
$state.go('home');
}
}]
}).state('challenge', {
url: '/challenges',
templateUrl: 'views/Challenges.html',
controller: 'ChallengeCtrl',
onEnter: ['$state', 'auth', function($state, auth) {
if (!auth.isLoggedIn()) {
$state.go('login');
}
}]
}).state('profile', {
url: '/profile',
templateUrl: 'views/Profile.html',
controller: "ProfileCtrl",
onEnter: ['$state', 'auth', function($state, auth) {
if (!auth.isLoggedIn()) {
$state.go('login');
}
}]
}).state('policy', {
url: '/policy',
templateUrl: 'views/Policy.html',
controller: 'AppCtrl'
}).state('cookie', {
url: '/cookie',
templateUrl: 'views/Cookie.html',
controller: 'AppCtrl'
}).state('challengesdone', {
url: '/challengesdone',
templateUrl: 'views/Challengesdone.html',
controller: 'ChallengesDoneCtrl',
onEnter: ['$state', 'auth', function($state, auth) {
if (!auth.isLoggedIn()) {
$state.go('login');
}
}]
}).state('forgot', {
url: '/forgot',
templateUrl: 'views/Forgot.html',
controller: 'UserCtrl'
}).state('reset', {
url: '/reset?sptoken',
templateUrl: 'views/Reset.html',
controller: 'UserCtrl'
});
$urlRouterProvider.otherwise('home');
}]);
Can this be accomplished without the use of external libraries and are there alot of adjustments needed?
You need to use $controllerProvider in your config.
app._controller = app.controller
app.controller = function (name, constructor){
$controllerProvider.register(name, constructor);
return (this);
};
And then resolve this method in your route.
.state('reset', {
url: '/reset?sptoken',
controller: 'UserCtrl',
resolve: {
deps : function ($q, $rootScope) {
var deferred = $q.defer();
require(["js/userCtrl"], function (tt) {
$rootScope.$apply(function () {
deferred.resolve();
});
deferred.resolve()
});
return deferred.promise;
}
},
templateUrl: 'views/Reset.html'
});
I have put together a CodePen for your.

Issue in passing url parameter

Here is my Controller
.when('/showprofile/:UserID', {
templateUrl: 'resources/views/layout/showprofdile.php',
controller: 'renameShowCtrl',
})
I have a url like this
http://192.168.1.58/myapp/#/showprofile/8
When I click the link it redirect me to
http://192.168.1.58/myapp/#/showprofile/:UserID
Here is my entire app.js
var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'toaster']);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/login', {
title: 'Login',
templateUrl: 'resources/views/layout/login.php',
controller: 'authCtrl'
})
.when('/logout', {
title: 'Logout',
templateUrl: 'resources/views/layout/login.php',
controller: 'logoutCtrl'
})
.when('/signin', {
title: 'Signup',
templateUrl: 'resources/views/layout/signin.php',
controller: 'authCtrl'
})
.when('/registersuccess', {
title: 'Dashboard',
templateUrl: 'resources/views/layout/register-success.php',
controller: 'authCtrl'
})
.when('/dashboard', {
title: 'Dashboards',
templateUrl: 'resources/views/layout/dashboard.php',
controller: 'authCtrl'
})
.when('/profile', {
title: 'Profile',
templateUrl: 'resources/views/layout/profile.php',
controller: 'authCtrl'
})
.when('/contact', {
title: 'Contact',
templateUrl: 'resources/views/layout/contact.php',
controller: 'authCtrl'
})
.when('/travel', {
title: 'Travel',
templateUrl: 'resources/views/layout/travel.php',
controller: 'authCtrl'
})
.when('/subscription', {
title: 'Subscription',
templateUrl: 'resources/views/layout/subscription.php',
controller: 'authCtrl'
})
.when('/invite_friends', {
title: 'InviteFriends',
templateUrl: 'resources/views/layout/invite_friends.php',
controller: 'authCtrl'
})
.when('/liked_you', {
title: 'LikedYou',
templateUrl: 'resources/views/layout/liked_you.php',
controller: 'authCtrl'
})
.when('/favourites', {
title: 'Favourites',
templateUrl: 'resources/views/layout/favourites.php',
controller: 'authCtrl'
})
.when('/coins', {
title: 'Subscription',
templateUrl: 'resources/views/layout/coins.php',
controller: 'authCtrl'
})
.when('/forget', {
title: 'forget',
templateUrl: 'resources/views/layout/forget.php',
controller: 'authCtrl'
})
.when('/verify', {
title: 'verfiy',
templateUrl: 'resources/views/layout/verify.php',
controller: 'authCtrl'
})
.when('/verifyfb', {
title: 'verfiyfb',
templateUrl: 'resources/views/layout/verifyfb.php',
controller: 'authCtrl'
})
.when('/registration', {
title: 'verfiy',
templateUrl: 'resources/views/layout/registration.php',
controller: 'authCtrl'
})
.when('/showprofile/:UserID', {
templateUrl: 'resources/views/layout/showprofdile.php',
controller: 'renameShowCtrl',
})
.when('/', {
title: 'Login',
templateUrl: 'resources/views/layout/login.php',
controller: 'authCtrl',
role: '0'
})
.when('/invalidtoken', {
title: 'Login',
templateUrl: 'resources/views/layout/invalidtoken.php',
controller: 'authCtrl',
role: '0'
})
}])
.run(function ($rootScope, $location, Data, $http) {
$rootScope.$on("$routeChangeStart", function (event, next, current) {
$http.post('CheckSession', {}).then(function (results)
{
console.log(results.data);
var nextUrl = next.$$route.originalPath;
if (nextUrl == '/signin' || nextUrl == '/login' || nextUrl == '/verify' || nextUrl == '/registration' || nextUrl == '/forget' || nextUrl == '/invalidtoken' || nextUrl == '/registersuccess')
{
console.log('outpages');
}
else
{
if (results.data == 1)
{
console.log('loggedin');
console.log(nextUrl);
;
console.log('to be redirect');
$location.path(nextUrl);
}
else {
console.log('not logged in');
$location.path('login');
}
}
});
});
});
app.controller('ShowOrderController', function($scope, $routeParams) {
$scope.UserIDs = $routeParams.UserIDs;
});
$scope.customNavigate=function(msg){
$location.path("/view2"+msg)
}
How can I display the parameter 8 in my view ?
Here is my authCtrl.js
Help pls
I am helping my friend question..
You can use $routeParams to get route paramaters.
In your case, your code in controller might look like:
function ctrl($scope, $routeParams) {
$scope.userId = $routeParams.UserID
}
In your view use binding expression {{userId}}
the right way is to pass the id parameter in url is
/showprofile/{UserID}

How to redirect to dashboard if user is logged in with AngularJS?

I am new in AngularJS. I want to redirect my page to dashboard if user is logged in. After login, i am getting access token which I am saving in cookies. I checked the solutions of Stack Overflow, then also my problem is not solved.
Here is my code:
app.js
(function(window){
var app= angular.module('customersApp',['ngRoute','ngCookies','ui.bootstrap']);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/login', {
title: 'Login',
controller: 'loginController',
templateUrl: 'app/views/loginuser.html'
})
.when('/logout', {
title: 'Logout',
templateUrl: 'partials/login.html',
controller: 'loginController'
})
.when('/dashboard', {
title: 'Dashboard',
templateUrl: 'app/views/dynamic_table.html',
controller: 'dashboard'
})
.when('/verified_artists', {
title: 'Verified Artists',
templateUrl: 'app/views/verified_artists.html',
controller: 'artistController'
})
.when('/new_artists', {
title: 'New Request Artists',
templateUrl: 'app/views/new_artists.html',
controller: 'artistController'
})
.otherwise({
redirectTo: '/login'
});
}]);
window.app = app;
}(window));
loginController.js
app.controller('loginController', function ($scope,$http,$cookies,$cookieStore) {
//initially set those objects to null to avoid undefined error
$scope.login = {};
$scope.signup = {};
$scope.doLogin = function (customer) {
$.post("websiteurl.com/admin_login",
{
user_email : $scope.login.email,
password : $scope.login.password
},
function(data,status){
data = JSON.parse(data);
console.log(data);
var someSessionObj = { 'accesstoken' : data.access_token};
$cookies.dotobject = someSessionObj;
$scope.usingCookies = { 'cookies.dotobject' : $cookies.dotobject, "cookieStore.get" : $cookieStore.get('dotobject') };
$cookieStore.put('obj', someSessionObj);
$scope.usingCookieStore = { "cookieStore.get" : $cookieStore.get('obj'), 'cookies.dotobject' : $cookies.obj, };
console.log($cookieStore.get('obj').accesstoken);
if(data.flag==10)
{
alert(data.error);
}
else
{
window.location.href = "#/dashboard";
}
})
};
});
try to look for route change event and check for cookie using cookie store...
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
// check for the cookie
// if present
// check next route
// if its login/signup page
// event.preventDefault(); (don't make the route change, redirect to dashboard)
// $location.path("/dashboard");
// if it is some other route
// allow it.
// if cookie not present
// $location.path("/login");
});

Categories