Page redirect not working in function - javascript

I want to refresh my entire page in the success function like this.
What i am trying to do is in the success function i am redirecting to /login and reloading the page.
if (results.data == 'success') {
$location.path('/login');
$location.reload();
}
I am redirected to /login but the page isn't refreshing. It throws error in the console like TypeError: $location.reload is not a function.
How can i fix this and reload the page once after $location.path('/login'); ?
Note : I am doing this in my controller

Did you inject the $location service in your controller?
You can also try $route.reload(), be sure to inject this service as well.

window.location.assign("/login")

You have to config your $routeProvider
mainApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'login.html',
controller: "loginController"
})
});
Then you can redirect the path using
$location.path('login');
anywhere in your controller.

Try with:
$route.reload();
And make sure to add "$route" when declaring the dependencies of your Controller.

try this location.reload(true)

Try this:
window.location.assign("http://localhost/testlogin.php");

you can try this..
if (results.data == 'success') {
$location.path('/login');
echo "<script>location.reload();</script>";
}

Related

Load 404 state with AngularJS Router

I am using AngularJS and ui-router and have the following code which catches 404's and loads in a 404 template:
$urlRouterProvider.otherwise(function($injector, $location){
$injector.invoke(['$state', function($state) {
$state.go('404');
}]);
});
It keeps the URL intact instead of redirecting, but shows the 404 template:
.state('404',
{
views: {
'body': {
templateUrl: 'partials/404.html',
}
}
});
Normally it would redirect to the root state with: $urlRouterProvider.otherwise('/');
However when HTML5 mode is turned off and the user visits the root URL e.g. http://www.domain.com/app/ it loads the 404 state instead of redirecting to http://www.domain.com/app/#/
How can I keep the 404 state code above, but have it redirect to the hashbang when accessing the initial page? So effectively only have the 404 load if the request is anything other than the home page?
I can't use the $stateNotFound or $stateChangeSuccess and need a way to check if it's a home page request within the actual config setup itself that can toggle between the / and the state.404 within the otherwise statement.
So something along the lines of (which does seem to work).
$urlRouterProvider.otherwise(function($injector, $location){
$injector.invoke(['$state', function($state) {
if( $location.$$path == '')
$state.go('home'); // redirect to /#/
else
$state.go('404'); // else go to 404 state
}]);
});
But is there a better way to handle this?
Use a httpErrorResponseInterceptor! This will get fired when a httpResponse happens. Here is an example
angular
.module('myApp')
.factory('httpErrorResponseInterceptor', ['$q', '$state', function ($q, $state) {
return {
responseError: function error(response) {
switch (response.status) {
case 404:
$state.go('404');
break;
default:
console.log("Unhandled HTTP error:", response);
}
return $q.reject(response);
}
};
}
]);

Pretty Urls in AngularJs and Laravel not working

I'm developing an application using Laravel and AngularJS. For AngularJS pretty URL , i have set $locationProvider.html5Mode(true) and it's working fine. But suppose my url is http://localhost:8000/demo and if i refresh the page, I'm getting NotFoundHttpException in compiled.php line 7693:
Here is my angular's routes.
function($routeProvider,$locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/', {
templateUrl: 'partials/index.html',
controller: 'indexController'
}).
when('/dom',{
templateUrl:'partials/dom.html',
controller:'DomController'
}).
when('/demo',{
templateUrl:'partials/demo.html',
controller:'DemoController'
});
}]);
And here's my laravel's route.
Route::get('/', function(){
return view('index');
});
I'd appreciate a little help.
Thanks!
The problem here is that the web server will pick up http://localhost:8000/demo when you refresh the page, and try to handle the request. It's not aware that you wish to use html5 routing. So it will parse the request, say "oh, I should pass this to public/index.php and be done with it". And then public/index.php will receive it and throw an error since the route doesn't exist in Laravel.
What you need to do is to make a catch all type of route in Laravel, and then let Angular's routing take over. You then render your index view on every single request. There's a great answer here on SO on how you do that in Laravel 5: How do I catch exceptions / missing pages in Laravel 5?
This is pseudo code and will not work, just to show an example:
Route::get('*', function() {
return view('index');
});
So, render the index view on every request and then let Angular handle the routing from there.

Protecting routes with authentication in an AngularJS app

Some of my AngularJS routes are to pages which require the user to be authenticated with my API. In those cases, I'd like the user to be redirected to the login page so they can authenticate. For example, if a guest accesses /account/settings, they should be redirected to the login form.
From brainstorming I came up with listening for the $locationChangeStart event and if it's a location which requires authentication then redirect the user to the login form. I can do that simple enough in my applications run() event:
.run(['$rootScope', function($rootScope) {
$rootScope.$on('$locationChangeStart', function(event) {
// Decide if this location required an authenticated user and redirect appropriately
});
}]);
The next step is keeping a list of all my applications routes that require authentication, so I tried adding them as parameters to my $routeProvider:
$routeProvider.when('/account/settings', {templateUrl: '/partials/account/settings.html', controller: 'AccountSettingCtrl', requiresAuthentication: true});
But I don't see any way to get the requiresAuthentication key from within the $locationChangeStart event.
Am I overthinking this? I tried to find a way for Angular to do this natively but couldn't find anything.
What I did is implement an angularjs interceptor which handles http request errors. Basically, what I do is when I get the 401 (unauthorized) from my backend, I save the current url and redirect the user to a login page. When the user does login successfully, I retrieve the saved url to set the path with $location.
app.config(function ($routeProvider, $locationProvider, $httpProvider) {
/* Global interceptor for 401 - not authorized */
var interceptor = ['$location', '$q', 'authorizationService', function ($location, $q, authorizationService) {
function success(response) {
return response;
}
function error(response) {
if (response.status === 401) {
authorizationService.saveUrl($location.path());
$location.path('/logon');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
return function (promise) {
return promise.then(success, error);
};
} ];
});
In the logon controller (on successful logon) I set the location like this:
$location.path(authorizationService.getUrl());
I use angular-http-auth in my project. If you have a backend is easier to delegate on it to handle the authentication, showing a login form automatically in each 401 response, than duplicate the authentication mapping both on client and server.

AngularJS ReferenceError: $window is not defined

I'm trying to re-direct my users if they pass my form validation (checking usernames and passwords against database values).
The validation works fine but in my .Success function the redirect doesn't seem to be working, it produces the error: 'ReferenceError: $window is not defined'.
Here's the code:
.success(function(data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorUserName = data.errors.userName;
$scope.errorUserPassword = data.errors.userPassword;
} else {
// if successful, bind success message to message
$scope.message = data.message;
$window.location=('twitter.com');
}
});
I've tried changing the location path but nothing seems to be working. Any ideas?
Thanks!
LazyTotoro
$window needs to be injected.
To inject it you simply add it as a parameter to your controller function and Angular will automatically take care of the rest.
For example:
app.controller('MyController', function MyController($scope, $window) {
$window.location = 'http://stackoverflow.com'
});
You can read more about dependency injection in AngularJS here.
If you don't need a full page reload you should instead inject and use $location:
// get the current path
$location.path();
// change the path
$location.path('/newValue');

AngularJS - evaluate a cookie in routes & template

I'm trying to sort out a login system using cookies so that the user's login will persist after leaving the app. I am able to set the cookie correctly, but I am unclear as to how I can use the stored cookie to limit the users access to the login screen if they are already logged in.
I think the best way to do this would be within the routes. This is what my file currently looks like:
var routes = angular.module('we365', ['rcForm', 'ngCookie', 'ngCookies']);
routes.config(function ($routeProvider) {
$routeProvider
.when('/login', {
templateUrl: 'views/login.html',
controller: 'loginCtrl'
})
.when('/', {// get digest view
templateUrl: 'views/getDigest.html',
controller: 'GetDigestCtrl'
})
.when('/artifact/:artifact_id', {// single artifact view
templateUrl: 'views/artifact.html',
controller: 'artifactCtrl'
})
.otherwise({
redirectTo: '/'
});
});
Also, i'd like to hide the 'login' button from the parent view so that the user isn't able to click on it. This is what the view looks like now:
<div class="container">
<div class="page-header col col-lg-12">
<h1>Welcome!</h1>
Login
Load Digest Data
</div>
</div>
There are many ways, I have two that are my favorite:
1) Check on route change
angular.module('MyApp', [])
.run(function($rootScope, myLoginService) {
$rootScope.$on('$routeChangeStart', function () {
if (!myLoginService.isUserLoggedIn()) {
$location.path('/login');
}
});
You can replace the isUserLogged for a mapper service that receives where the user wants to go; if the user has the proper privileges (either stored within a cookie or local storage in the form of a token), then let the route succeed. Otherwise, show an error, or route him to wherever you want. In my case, the myLoginService checks for a localStorage.
2) Any data request to a server has a token included to headers; failed requests (401) are intercepted and stored, while the user is redirected
This one is more for CRUD apps and not necessarily for routing, but the concept is simple: a user A can perform N actions as long as he/she has the privileges to do so; if he tries to perform an action (or M actions) that he's not allowed, then the request is intercepted and queued in order to ask him to authenticate with a user that CAN do those actions
.factory('securityInterceptor', ['$injector', 'securityRetryQueue', function($injector, queue) {
return function(promise) {
// Intercept failed requests
return promise.then(null, function(originalResponse) {
if(originalResponse.status === 401) {
// The request bounced because it was not authorized - add a new request to the retry queue
promise = queue.pushRetryFn('unauthorized-server', function retryRequest() {
// We must use $injector to get the $http service to prevent circular dependency
return $injector.get('$http')(originalResponse.config);
});
}
return promise;
});
};
}]);
Again, this is for more "data like" requests and not necessarily for routing. This was stolen from the AngularJS sample app. You should check it for more examples.

Categories