StateParams are empty on page refresh using the ui-router - angularjs

I use angular's ui-router and nested routes in a project and I'm faced by the problem that everything works like a charm when I use links (ui-sref) to navigate to the user's detail page with the userId as part of the url. When I refresh the page, state params are missing.
So I've taken a look at the angular demo: http://angular-ui.github.io/ui-router/sample/#/contacts/1/item/b and couldn't reproduce this behaviour, however nested states are not part of this demo in contrast to my application.
$stateProvider
.state('base', {
abstract: true
})
.state('home', {
parent: 'base',
url: '/',
views: {
'content#': {
templateUrl: 'app/index/index.view.html',
controller: 'IndexController',
controllerAs: 'home'
}
}
})
.state('users', {
url: '/users',
parent: 'base',
abstract: true
})
.state('users.list', {
url: '/list',
views: {
'content#': {
templateUrl: 'app/users/users.list.html',
controller: 'UsersController',
controllerAs: 'users'
}
},
permissions: {
authorizedRoles: UserRoles.ALL_ROLES
}
})
.state('users.details', {
url: '/:userId/details',
views: {
'content#': {
templateUrl: 'app/users/user.details.html',
controller: 'UserDetailsController',
controllerAs: 'userDetails'
}
},
resolve: {
logSomeParams: ['$stateParams', '$state', function ($stateParams, $state) {
console.log($stateParams);
console.log(this);
console.log($state);
}]
}
})
When refreshing the page the url immediately changes to http://localhost:3000/#/users//details and console output (resolve function) shows that params are missing.
html5Mode (LocationProvider) is not enabled. I already found "solutions" like redirecting back to the list if the the userId is missing on page refresh, but I just can't believe that there isn't a better way to solve this.
This is how I linked the details page in the overview (and it is working):
<div class="panel-body" ui-sref="users.details({userId: user.siloUserId})">

As expected, my problem had nothing to do with the ui-router. The URLMatcher works as expected, even if you refresh the page (everything else would have been a huge dissapointment).
However, I have a $stateChangeStart listener which checks if the SAML authentication session (cookie) is still valid and waits for the result.
function(event, toState, toParams, fromState, fromParams){
if(!authenticationService.isInitialized()) {
event.preventDefault();
authenticationService.getDeferred().then(() => {
$state.go(toState);
});
} else {
//check authorization
if ( authenticationService.protectedState(toState) && !authenticationService.isAuthorized(toState.permissions.authorizedRoles)) {
authenticationService.denyAccess();
event.preventDefault();
}
}
}
No idea how this could happen, but I forgot to pass the parameters to the go method of the stateProvider. So all I had to change was to add the params:
$state.go(toState, toParams);

Related

How to properly redirect in angular UI-Router

I am trying to use resolve and conditional routing in angular ui-router but it doesnt seem to work
App.js:
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/home.html'
})
.state('app.login', {
url: '/login',
views: {
'menuContent': {
templateUrl: 'templates/login.html'
}
}
})
.state('app.therapist', {
url: '/therapist',
views: {
'menuContent': {
templateUrl: 'templates/therapist.html'
}
}
}).state('app.trial', {
url: '/trial',
views: {
'menuContent': {
templateUrl: 'templates/trial.html'
}
},
resolve:{
check:function($state){
if(1==1){
e.preventDefault();
$state.go('app.login',{}) ; /**/Here trying**
}else{
return true;
}
}
}
$urlRouterProvider.otherwise('/app/therapist');
});
So in app.trail route I was testing and trying to redirect to app.login but it doesnt work it only opens the trial page
In e.preventDefault(); you appear to be missing anything defined as e.
You can use preventDefault() when handling an event such as $stateChangeStart, but I don't think that is available within resolve.
See Angular ui-router $state.go is not redirecting inside resolve for some suggestions on how to handle this (do the check inside a handler for $stateChangeStart, or send an event to trigger the transition, or use a timeout to delay your state change until after the first one has completed).

Redirect to different ui-router state with same url from server?

Currently I have a state 'home' which resides at the url '/'. After a user connects, the 'client' state is loaded, which also resides at the url '/' and the session is updated. Is it possible to make it so that if the user reloads the page, the 'client' state is loaded immediately instead of the 'home' state? If they were at different urls, I could simply have the server perform a redirect but I would like them both to be at the base url '/'. Is there some functionality in ui-router that would let me achieve this?
Here are my states:
app.config(function($stateProvider, $urlRouterProvider,$locationProvider) {
$stateProvider
.state('home', {
url: '/',
controller: 'HomePageConroller as homeCtrl',
templateUrl: '/views/partials/home.html',
onEnter: function($http,$state) {
$http.post('/checkconnected')
.success(function(data,status) {
if (data) {$state.go('client');}
});
}
})
.state('client', {
url: '/',
controller: 'ClientController as clientCtrl',
templateUrl: '/views/partials/client.html'
});
As you can see I am currently posting a check to the server to see if the client is connected and then doing a redirect from within the angular application, but I am not happy with this solution at all. The post takes time and so the home page is fully loaded and seen by the user before the client page is shown.
One solution I have considered is having another state called 'client redirect' that does reside at '/client' and has the same template as the 'client' state, which does the same $state.go on enter without the need of an $http.post (because the server already redirected based on the updated session). This would remove the delay and not flash the homescreen, however it does not seem elegant.
var app = angular.module("app", [
"ui.router"
]);
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/index');
$stateProvider
.state("app", {
abstract: true,
url: '/app',
templateUrl: "views/layout/app-body.html"
})
.state("index", {
url: "/index",
templateUrl: "views/home.html",
controller: 'signinController'
})
.state("signin", {
url: "/signin",
templateUrl: "views/pages/signin.html",
controller: 'signinController'
})
.state("signup", {
url: "/signup",
templateUrl: "views/pages/signup.html",
controller: 'signupController'
})
.state('app.home', {
url: '/home',
templateUrl: 'views/home/home.html',
controller: 'homeController'
})
.state('app.dashboard', {
url: '/dashboard',
templateUrl: 'views/dashboard/dashboard.html',
controller: 'dashboardController'
})
.state('app.profile', {
url: '/profile',
templateUrl: 'views/pages/profile.html',
controller: 'profileController'
});
});
Visit http://embed.plnkr.co/IzimSVsstarlFviAm7S7/preview?
Okay here is how I solved this. I renamed the url of 'client' from '/' to '/client'. On my server the get request checks if the user is connected and redirects to get '/client' if so (which renders the exact same angular app only the url is different). Then I modified my client to state to onEnter change $location.path(). Realizing this is practically the same as $state.go, I used the event handler for $stateChangeStart to prevent the state transition. Final code looks like this:
app.config(function($stateProvider, $urlRouterProvider,$locationProvider) {
$stateProvider
.state('home', {
url: '/',
controller: 'HomePageConroller as homeCtrl',
templateUrl: '/views/partials/home.html'
})
.state('client', {
url: '/client',
controller: 'ClientController as clientCtrl',
templateUrl: '/views/partials/client.html',
onEnter: function($location){$location.path('/');}
});
$urlRouterProvider.otherwise('/');
$locationProvider.html5Mode(true);
});
app.run(['$rootScope', function($rootScope) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
if (fromState.name == 'client' && toState.name == 'home') {
event.preventDefault();
}
});
}]);
If I can clean this up further please comment below.

AngularJs using resolve in $state with ui-router

hi im trying to get an example app up and running and I cannot get it to load the view.. here is the complete app.js however i think the error is within the resolve object... any help or guidance would be apprieciated... thanks for looking
here is the github link for the project....
i will change api key after this issue is solved
https://github.com/ChrisG000/stamplayEbayClassified
angular.module('starter', ['ionic', 'starter.controllers','starter.services', 'starter.templatesComponent', 'ngCordova'])
.run(function($ionicPlatform, $cordovaStatusbar) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
// org.apache.cordova.statusbar required
$cordovaStatusbar.styleColor('white');
//StatusBar.styleDefault();
}
});
})
.constant('APPID', '')
.constant('APIKEY','')
.constant('BASEURL', '')
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
abstract: true,
templateUrl: "templates/tabs.html",
resolve: {
category: function (Category) {
return Category.getPromise();
},
areas : function(Area){
return Area.getPromise();
},
items : function(Item){
return Item.getPromise();
}
},
})
// Each tab has its own nav history stack:
.state('tab.item', {
url: '/item',
views: {
'tab-item': {
templateUrl: 'templates/tab-item.html',
controller: 'FindCtrl'
}
},
})
.state('tab.item-view', {
url: '/item/:itemId',
views: {
'tab-item': {
templateUrl: 'templates/item-view.html',
controller: 'ItemCtrl'
}
}
})
.state('tab.publish', {
url: '/publish',
views: {
'tab-publish': {
templateUrl: 'templates/tab-publish.html',
controller: 'PublishCtrl'
}
}
})
.state('tab.account', {
url: '/account',
views: {
'tab-account': {
templateUrl: 'templates/tab-account.html',
controller: 'AccountCtrl'
}
}
})
.state('tab.settings', {
url: '/settings',
views: {
'tab-settings': {
templateUrl: 'templates/tab-settings.html',
controller: 'SettingsCtrl'
}
}
})
.state('tab.login', {
url: '/settings/login',
views: {
'tab-settings': {
templateUrl: 'templates/login-view.html',
controller: 'LoginCtrl'
}
}
})
.state('tab.signup', {
url: '/settings/signup',
views: {
'tab-settings': {
templateUrl: 'templates/signup-view.html',
controller: 'LoginCtrl'
}
}
})
.state('tab.contact', {
url: '/settings/contact',
views: {
'tab-settings': {
templateUrl: 'templates/contact-view.html',
controller: 'SettingsCtrl'
}
}
})
.state('tab.terms', {
url: '/settings/terms',
views: {
'tab-settings': {
templateUrl: 'templates/terms-view.html',
controller: 'SettingsCtrl'
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/item');
});
Ok, here's how you would diagnose something like this. First you want to avoid the loop because that makes it really hard to figure out what's going on. Since the problem is happening on your default route, the solution is to temporarily change your default route to something else. Then, you'll go to localhost:8100/#/item manually. In this scenario you'll avoid the loop and you'll be able to look in the Chrome DevTools to see what's happening without having an infinite loop that locks up the DevTools.
First, change your app.js file to include the following simple route:
.state('testing', {
url: '/testing',
template: '<h1>Testing</h1>'
})
Also in app.js (line 143), change your default route to go to our simple route:
$urlRouterProvider.otherwise('/testing');
Now, in your browser, visit http://localhost:8100/#/item directly while you have the DevTools open. Before actually hitting enter, make sure you set the Network and Console tabs configured to "Preserve log" (it is a checkbox). This way, even though you're redirected to /testing because there is an error, you'll actually be able to see the error in the DevTools console.
In your case, the error is a 404 error on the OPTIONS request that is sent to http://localfood.stamplay.com/api/cobject/v0/category. You can read up on CORS and ionic here: http://blog.ionic.io/handling-cors-issues-in-ionic/
Additionally, when I try to visit http://localfood.stamplay.com/api/cobject/v0/category directly I am greeted with a too many redirects error in my browser, which means that something is not configured correctly on the api server. The server should respond with some kind of error at /error but instead it keeps redirecting to itself.
Bottom line, it looks like a server configuration issue.
Edit: When using the updated url http://localfood.stamplayapp.com/api/cobject/v0/category I get a 403 Forbidden so my guess is that OP changed the api key after posting this but that this did resolve his issue.

Angularjs - one route two possible views

I want to be able to use one single route for two different views.
For example right now, I have two routes.
One is /home which is the main page when someone can register/login
And the other one /feed, this is when the user is logged in.
What I want to do is having a single route like twitter for example :
twitter.com/
first they ask you to login
twitter.com/
Than we can see our feed wall. And it's still the same "/". Hope I'm clear :)
This is my code so far:
$stateProvider
.state('index', {
url: '/',
controller: function($state, $auth) {
$auth.validateUser()
.then(function(resp) {
$state.go('feed');
})
.catch(function(resp) {
$state.go('home');
});
}
})
.state('home', {
url: '/home',
templateUrl: 'home.html'
})
.state('feed', {
url: '/feed',
templateUrl: 'feed.html'
})
As far as I remember ui-router doesn't support such feature so you have to do it yourself.
What you can do is to define only a single state as you did in 'index' and instead of performing the $auth logic in the controller do it in a the "resolve" section.
then you can use "ng-if" and "ng-include" to define which .html file and controller you'd like to load, something like this:
app.js
$stateProvider
.state('index', {
url: '/',
resolve: {
isAuthenticated: function() {
return $auth.validateUser().then(function(res) {
return true;
}, function(error) {
return false;
});
}
},
controller: function($scope, isAuthenticated) {
$scope.isAuthenticated = isAuthenticated;
},
templateUrl: 'index.html'
})
index.html
<div ng-if="isAuthenticated">
<div ng-include="'feed.html'"></div>
</div>
<div ng-if="!isAuthenticated">
<div ng-include="'login.html'"></div>
</div>

Angular ui-router: How to defer rendering the template until authorization is complete?

My ui-router configuration is this:
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'sidemenu/sidemenu.html',
controller: 'SideMenuCtrl'
})
.state('login', {
url: '/login',
templateUrl: 'login/login.html',
controller: 'LoginCtrl'
})
.state('app.dashboard', {
url: '/dashboard',
views: {
menuContent: {
templateUrl: 'dashboard/dashboard.html',
controller: 'DashboardCtrl'
}
}
})
[More states here]
$urlRouterProvider.otherwise('/app/dashboard');
When user navigates to /app/dashboard I would like to check if they are authorized, and then:
redirect to /login if they are not authorized, or
allow to see the dashboard if they are authorized
This seems to do the trick: (based on this example)
$rootScope.$on('$stateChangeSuccess', function(event) {
var path = $location.path();
if (path === '/login') {
return;
}
// Halt state change from even starting
event.preventDefault();
Auth.getCurrentUser().then(function(currentUser) {
if (currentUser === null) {
$state.go('login');
} else {
// Continue with the update and state transition
$urlRouter.sync();
}
});
});
The only problem with this solution is that, if a non-authorized user navigates to the dashboard, the dashboard template is visible first. Only when the authorization response is coming back it changes to the login template.
Is there a way not to show the dashboard while we authorize the user?
I also tried to change $stateChangeSuccess to $stateChangeStart, but it didn't really work (routing seems to be completely broken then).
What about using a resolve-block?
.state('app.dashboard', {
url: '/dashboard',
views: {
menuContent: {
templateUrl: 'dashboard/dashboard.html',
controller: 'DashboardCtrl',
resolve: {
login: function($q, Auth) {
var deferred = $q.defer();
Auth.getCurrentUser().then(function(currentUser) {
if (currentUser == null) {
deferred.reject();
} else {
deferred.resolve();
}
});
return deferred.promise;
}
}
}
}
})
The state-change won't happed untill the promise is resolved so the template should not be showing. Rejecting the promise will raise a $stateChangeError according to this answer so you would need to handle that error and redirect to the login-page.
You could use resolve on your routes and reject the promise when the user is not logged in, so the controller will never be reached.

Resources