How to get ui-router state parameters from resolved data in angularjs - javascript

How do I get parameters for a state from a service?
I have this state:
.state('cashbox.list', {
title: 'Cashbox',
url: '/:from/:to?q',
templateUrl: '/cashbox_list.html',
controllerUrl: 'controllers/CashboxCtrl.js',
controller: 'CashboxCtrl',
controllerAs: 'mainCtrl',
params: {
from: getCashboxParamFrom,
to: getCashboxParamTo
},
resolve: {
cashboxData: getTransactionsData
}
})
function getTransactionsData($stateParams)
{
return CashboxService.getTransactions($stateParams.from, $stateParams.to);
}
Now my problem is, that params from and to are dynamic and are fetched by another service. I need something like a resolve before the resolve to get the params. I already tried to operate with promises in getCashboxParamTo/From but the app then stops routing when going to state. Also tried to use a parent state with redirectTo into child state but don't find anything on how to dynamically create stateparams from resolved data in parent state.
.state('cashbox', {
title: trns('title.cashbox_list'),
url: '/cashbox',
redirectTo: {
state: 'cashbox.list',
params: HERE DATES FROM RESOLVE
},
resolve: {
dates: getFromToDates
}
})
Solutions with state.go won't work as I'm running into a 'The transition has been superseded by a different transition' issue.

The answer is to declare two states cashbox and cashbox.list. Then redirect in a onStart transition hook after fetching data from service:
$transitions.onStart({to: 'cashbox'}, function (trans)
{
var curMonth = gfService.getCurrentMonth();
return $state.target('cashbox.list', {from: curMonth.dateFrom.string, to: curMonth.dateTo.string})
});

Related

Angular ui-router resolve inheritance

I would like to create an abstract parent state, that has only one job: to resolve the current user through an ajax server call, and then pass this object to the child state. The problem is that the child state never gets loaded. Please have a look at this plunker: Example
a state
angular.module('test', ['ui.router'])
.config(function($stateProvider, $urlRouterProvider){
// Parent route
$stateProvider.state('main', {
abstract:true,
resolve: {
user: function(UserService){
return UserService.getUser();
}
}
});
// Child route
$stateProvider.state('home', {
parent: 'main',
url: '/',
controller: 'HomeController',
controllerAs: '$ctrl',
template: '<h1>{{$ctrl.user.name}}</h1>'
});
$urlRouterProvider.otherwise('/');
});
a factory
angular.module('test').factory('UserService', function($q){
function getUser() {
var deferred = $q.defer();
// Immediately resolve it
deferred.resolve({
name: 'Anonymous'
});
return deferred.promise;
}
return {
getUser: getUser
};
});
a controller
angular.module('test').controller('HomeController', function(user){
this.user = user;
});
In this example, the home state will never display the template, I don't really understand why. If I remove the parent: 'main' line, then it displays the template, but of course I get an error because it cannot find the user dependency in the HomeController.
What am I missing? I did everything like it is described in ui-router's documentation, I think this should work.
Every parent must have a target ui-view in template for its child
$stateProvider.state('main', {
abstract:true,
resolve: {
user: function(UserService){
return UserService.getUser();
}
}
template: '<div ui-view=""></div>'
});
NOTE: Another option is to use absolute names and target index.html .. but in this case the above is the way to go (Angularjs ui-router not reaching child controller)

How do I deal with Angular-UI-Router resolve with an unfulfilled promise?

Lets say I have a an angular ui router route set up. When I change to that state, I'm telling Angular that I want it to resolve a factory call first then load the view. But what happens when that api call is empty? I would like to inform the user that there was no results found and stay on at my original state. Not transition to another view with no data to display. What is the best way to achieve this?
The route (which works as expected so far when I know there will be a return)
'use strict';
angular.module('testApp')
.config(function ($stateProvider) {
$stateProvider
.state('spinnerTest', {
url: '/spinner_test',
templateUrl: 'app/spinnerTest/spinnerTest.html',
controller: 'SpinnerTestCtrl',
resolve: {
names: function(NamesService){
//What happens if I return an empty array []?
//How do I return to the previous state?
NamesService.getNames();
}
}
});
});
You can simply reject promise in resolve in case of empty array:
resolve: {
names: function(NamesService) {
return NamesService.getNames().then(function(names) {
return names.length == 0 ? $q.reject('no names') : names;
});
}
}
This is a cross cutting concern, it is probably not unique to the Name service, but other services you are using as well.
Since you didn't post the code to the Name service (NameService service is redundant) I will assume it uses either the $http or $resource service. You can then use a $httpInterceptor that will trigger the display of a message to the user that "The selection is unavailable at this time".
You could call $state.go in your resolve, if you'd like
'use strict';
angular.module('testApp')
.config(function ($stateProvider) {
$stateProvider
.state('spinnerTest', {
url: '/spinner_test',
templateUrl: 'app/spinnerTest/spinnerTest.html',
controller: 'SpinnerTestCtrl',
resolve: {
names: function(NamesService, $state){
//What happens if I return an empty array []?
//How do I return to the previous state?
return NamesService.getNames().then(function(names){
if (!names.length) {
return $state.go('otherState');
}
return names;
});
}
}
});
});

AngularJS ui-router: how to resolve typical data globally for all routes?

I have an AngularJS service which communicates with the server and returns
translations of different sections of the application:
angular
.module('utils')
.service('Translations', ['$q','$http',function($q, $http) {
translationsService = {
get: function(section) {
if (!promise) {
var q = $q.defer();
promise = $http
.get(
'/api/translations',
{
section: section
})
.success(function(data,status,headers,config) {
q.resolve(result.data);
})
.error(function(data,status,headers,config){
q.reject(status);
});
return q.promise;
}
}
};
return translationsService;
}]);
The name of the section is passed as the section parameter of the get function.
I'm using AngularJS ui-router module and following design pattern described here
So I have the following states config:
angular.module('app')
.config(['$stateProvider', function($stateProvider) {
$stateProvider
.state('users', {
url: '/users',
resolve: {
translations: ['Translations',
function(Translations) {
return Translations.get('users');
}
]
},
templateUrl: '/app/users/list.html',
controller: 'usersController',
controllerAs: 'vm'
})
.state('shifts', {
url: '/shifts',
resolve: {
translations: ['Translations',
function(Translations) {
return Translations.get('shifts');
}
]
},
templateUrl: '/app/shifts/list.html',
controller: 'shiftsController',
controllerAs: 'vm'
})
This works fine but as you may notice I have to explicitly specify translations in the resolve parameter. I think that's not good enough as this duplicates the logic.
Is there any way to resolve translations globally and avoid the code duplicates. I mean some kind of middleware.
I was thinking about listening for the $stateChangeStart, then get translations specific to the new state and bind them to controllers, but I have not found the way to do it.
Any advice will be appreciated greatly.
Important note:
In my case the resolved translations object must contain the translations data, not service/factory/whatever.
Kind regards.
Let me show you my approach. There is a working plunker
Let's have a translation.json like this:
{
"home" : "trans for home",
"parent" : "trans for parent",
"parent.child" : "trans for child"
}
Now, let's introduce the super parent state root
$stateProvider
.state('root', {
abstract: true,
template: '<div ui-view=""></div>',
resolve: ['Translations'
, function(Translations){return Translations.loadAll();}]
});
This super root state is not having any url (not effecting any child url). Now, we will silently inject that into every state:
$stateProvider
.state('home', {
parent: 'root',
url: "/home",
templateUrl: 'tpl.html',
})
.state('parent', {
parent: 'root',
url: "/parent",
templateUrl: 'tpl.html',
})
As we can see, we use setting parent - and do not effect/extend the original state name.
The root state is loading the translations at one shot via new method loadAll():
.service('Translations', ['$http'
,function($http) {
translationsService = {
data : {},
loadAll : function(){
return $http
.get("translations.json")
.then(function(response){
this.data = response.data;
return this.data;
})
},
get: function(section) {
return data[section];
}
};
return translationsService;
}])
We do not need $q at all. Our super root state just resolves that once... via $http and loadAll() method. All these are now loaded, and we can even place that service into $rootScope:
.run(['$rootScope', '$state', '$stateParams', 'Translations',
function ($rootScope, $state, $stateParams, Translations) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$rootScope.Translations = Translations;
}])
And we can access it anyhwere like this:
<h5>Translation</h5>
<pre>{{Translations.get($state.current.name) | json}}</pre>
Wow... that is solution profiting almost from each feature coming with UI-Router... I'd say. All loaded once. All inherited because of $rootScope and view inheritance... all available in any child state...
Check that all here.
Though this is a very old question, I'd like to post solution which I'm using now. Hope it will help somebody in the future.
After using some different approaches I came up with a beautiful angularjs pattern by John Papa
He suggest using a special service routerHelperProvider and configure states as a regular JS object. I'm not going to copy-paste the entire provider here. See the link above for details. But I'm going to show how I solved my problem by the means of that service.
Here is the part of code of that provider which takes the JS object and transforms it to the states configuration:
function configureStates(states, otherwisePath) {
states.forEach(function(state) {
$stateProvider.state(state.state, state.config);
});
I transformed it as follows:
function configureStates(states, otherwisePath) {
states.forEach(function(state) {
var resolveAlways = {
translations: ['Translations', function(Translations) {
if (state.translationCategory) {
return Translations.get(state.translationCategory);
} else {
return {};
}
}],
};
state.config.resolve =
angular.extend(state.config.resolve || {}, resolveAlways || {});
$stateProvider.state(state.state, state.config);
});
});
And my route configuration object now looks as follows:
{
state: ‘users’,
translationsCategory: ‘users’,
config: {
controller: ‘usersController’
controllerAs: ‘vm’,
url: ‘/users’.
templateUrl: ‘users.html'
}
So what I did:
I implemented the resolveAlways object which takes the custom translationsCategory property, injects the Translations service and resolves the necessary data. Now no need to do it everytime.

Angular one resolve for all states

I got a routeProvider for my states.
$routeProvider.
when("/register",{
templateUrl: "templates/register.html",
controller: "RegisterCtrl",
resolve: {
user: function(Auth) {
return Auth.resolveUser();
}
}
}).
when("/home",{
templateUrl: "templates/home.html",
controller: "HomeCtrl",
resolve: {
user: function(Auth) {
return Auth.resolveUser();
}
}
}). .... [.....]
Every state got a promise which resolves, when user-state is loggedIn. Then the code of the different controllers is executed. Now I want to have a mainController for the navigation bar, which should be present on all sites. The controller needs the userdata for checking for new messages etc.
Now: how is it possible to define the resolve globally in a root state (so i can access the userdata in the root controller for all sites) and all the other controllers execute their code only, if the promise from this roote state is resolved?
I hope I formulated my question understandable...
I think you're looking for something like $routeChangeStart, that is a way to execute something you want everytime the user changes his route inside your web app. Take a look at Route and this other question from stackoverflow. Hope it helps.
You can do this by defining your routes outside of the $routeProvider.when statements:
var routes = [
{
url: "/register",
config: {
templateUrl: "templates/register.html",
controller: "RegisterCtrl"
}
},
{
url: "/home",
config: {
templateUrl: "templates/home.html",
controller: "HomeCtrl"
}
}
];
Then iterating through your routes to extend the resolve property before registering them with the $routeProvider:
angular.forEach(routes, function (route) {
var url = route.url;
var routeConfig = route.config;
routeConfig.resolve = angular.extend(routeConfig.resolve || {}, {
// add your global resolves here
user: function(Auth) {
return Auth.resolveUser();
}
});
$routeProvider.when(url, routeConfig);
});
Your Auth.resolveUser() should be responsible for returning the fulfilled promise if it was already resolved previously.

Angular UI-Router passing data between states with go function does not work

I just started learning angularjs and I am using angular-ui-router. I am trying to send data from one state to another using $state.go but I have no success. Here is what I have so far:
I have not included the html intentionally because I assumed it was not needed if it is needed please tell me and I will add it.
I have configured my states as below:
$stateProvider
.state('public', {
abstract: true,
templateUrl: 'App/scripts/main/views/PublicContentParent.html'
})
.state('public.login', {
url: '/login',
templateUrl: 'App/scripts/login/views/login.html',
controller: 'loginCtrl'
})
$stateProvider
.state('private', {
abstract: true,
templateUrl: 'App/scripts/main/views/PrivateContentParent.html'
})
.state('private.visits', {
url: '/visits',
views: {
'main': {
controller: 'visitsListCtrl',
templateUrl: 'App/scripts/visits/views/VisitsList.html'
}
}
});
When my LoginController is invoked it will execute the below code:
loginModule.controller('loginCtrl', ['$state', function ($scope, $state) {
$state.go('private.visits', { name : "Object"});
}]);
When the private.visits page is active, I am trying to print the $stateParams:
visitsModule.controller('visitsListCtrl', ['$stateParams',
function ($stateParams) {
console.log($stateParams);
}]);
As things state $stateParams is an empty object. I expected it to to contain the object I passed in loginCtrl.
EDIT
It seems that if private.visits url has this url format '/visits/:name' and I also add the property params: ["name"] I get access to the object I send from the public.login state.
The side effect is that the parameters are added to the url which is logical.
I tried doing the same thing with a child state with no url, and in this case it seems that I do not have access to the params I passed from public.login.
How do I send data in child states?
What you have to do is to define the name param in the private.visits state like:
$stateProvider
.state('public', {
abstract: true,
templateUrl: 'App/scripts/main/views/PublicContentParent.html'
})
.state('public.login', {
url: '/login',
templateUrl: 'App/scripts/login/views/login.html',
controller: 'loginCtrl'
})
$stateProvider
.state('private', {
abstract: true,
templateUrl: 'App/scripts/main/views/PrivateContentParent.html'
})
.state('private.visits', {
// NOTE!
// Previously, we were only passing params as an array
// now we are sending it as an object. If you
// send this as an array it will throw an error
// stating id.match is not a function, so we updated
// this code. For further explanation please visit this
// url http://stackoverflow.com/a/26204095/1132354
params: {'name': null},
url: '/visits',
views: {
'main': {
controller: 'visitsListCtrl',
templateUrl: 'App/scripts/visits/views/VisitsList.html',
resolve: {
name: ['$stateParams', function($stateParams) {
return $stateParams.name;
}]
}
}
}
});
And then in the controller access to the name:
visitsModule.controller('visitsListCtrl', ['name',
function (name) {
console.log(name);
}]);
Hope it help you!
When you say:
$state.go('private.visits', { name : "Object"});
You're not passing data to the private.visits state, but rather you're setting a parameter to the private.visits state, which doesn't even support parameters as you have not defined parameters for it in the state config. If you want to share data between states use a service, or if your states have a parent-child relationship then the child state will have access to the parent states data. Seeing as how you don't want the data to sow up in your URLs, I would use a service (getters/setters) to achieve this.

Categories