Changing a request url based on url when using ui.route - angularjs

I am using $http in angular for ajax calls and using ui.router for routing.
Routes
.state("/dashboard.inactive", {
url: "/inactive",
templateUrl: "angular/templates/dashboard/inactive.html",
controller: "dashboardCtrl"
})
.state("/dashboard.drafts", {
url: "/drafts",
templateUrl: "angular/templates/dashboard/drafts.html",
controller: "dashboardCtrl"
});
So the below code works if it is for a single URL.
Controller
app.controller('dashboardCtrl', function ($scope, DashboardFactory){
DashboardFactory.listings(function(DashboardFactory) {
$scope.results = DashboardFactory;
});
});
Below factory is fetching only from drafts.json resource. So when the URL changes to inactive I want it to fetch from inactive.json and active.json respectively.
Factory
app.factory('DashboardFactory', function($http){
return {
listings: function(callback){
$http.get('drafts.json').success(callback);
}
};
});
In short I need to send requests to any one of the below 3 URLs based on the URL
1) '/drafts.json'
2) '/inactive.json'
3) '/active.json'
I can create a different controllers for each active, inactive and drafts and make it fetch as expected. But is there any better way to do this??

You could use the $state service of ui route in order to tell which state your are in.
Just inject $state to your service and then use $state.current in order to access the current state config.
app.factory('DashboardFactory',
function($http, $state){
return {
listings: function(callback){
var currentView = $state.current.url.replace('/', '');
$http.get(currentView + '.json').success(callback);
}
};
});
A better solution would be to either use the params property of the state config or add some custom property like:
.state("/dashboard.inactive", {
url: "/inactive",
templateUrl: "angular/templates/dashboard/inactive.html",
controller: "dashboardCtrl",
params: {
json: 'inactive.json'
}
})
.state("/dashboard.drafts", {
url: "/drafts",
templateUrl: "angular/templates/dashboard/drafts.html",
controller: "dashboardCtrl",
params: {
json: 'drafts.json'
}
});
It is described in the documentation.

Related

Is it possible to use resolves outside of states?

I have site navigation that doesn't exist in any particular state. It's always available along the top of the page, regardless of which state the application is in.
I need to hide/show certain menu options depending on who the user is. I'm using windows authentication so a trip to the server is a necessity. The problem is since the nav bar doesn't belong to any particular state I don't know where to put the resolve.
Is there something like a global state which would be resolved first before any other states where I could put the resolve?
Something like:
.state('$global', {
url: '/',
templateUrl: 'partials/navigation/navbar.html',
controller: 'NavCtrl',
resolve: {
navData: ['$http', 'SettingsFactory', 'ViewMatrixService', function($http, SettingsFactory, ViewMatrixService) {
return $http.get(SettingsFactory.APIUrl + 'api/nav', { withCredentials: true }).then(function (response) {
ViewMatrixService.GenerateHomeViewMatrix(response.data.CurrentUser);
return response.data;
});
}]
}
})
I considered using $broadcast but then I'd need to make sure every possible point of entry to the application gets the information the nav bar needs from the server and broadcasts it which contaminates all my other controllers with nav bar responsibilities.
I was unable to find a way to use resolves outside of states, but I did find a solution.
I created an abstract parent state called app. I have a resolve in app that gets the user's profile. Then it can be injected into any child state controllers.
Since the nav bar is stateless, in the same resolve I pass the currentUser object to a service which is used across the app to store visibility and disabled flags for all controls.
It looks like this:
$stateProvider
.state('app', {
abstract: true,
template: '<ui-view/>',
resolve: {
currentUser: ['$http', 'SettingsFactory', 'ViewMatrixService', function($http, SettingsFactory, ViewMatrixService) {
return $http.get(SettingsFactory.APIUrl + 'api/users/current', { withCredentials: true }).then(function (response) {
ViewMatrixService.GenerateHomeViewMatrix(response.data);
return response.data;
});
}
]}
})
.state('app.home', {
url: '/',
templateUrl: 'partials/home.html',
controller: 'HomepageCtrl',
resolve: {
homeData: ['$http', 'SettingsFactory', function($http, SettingsFactory) {
return $http.get(SettingsFactory.APIUrl + 'api/home', { withCredentials: true }).then(function (response) {
return response.data;
});
}]
}
})
.state('app.userProfiles', {
url: '/admin/users',
templateUrl: 'partials/admin/user-profiles.html',
controller: 'UserProfilesCtrl'
})...

angular ui-router- ajax call on load

We are developing an single page application using angular JS and I am using state provider for configuring routes. Basically there is a global navigation view and a dashboard view. I have to pass few params from navigation to make a service call and then display the dashboard accordingly.I have split the states as two, one for navigation and other for dashboard. THe thing which i am not able to figure out is that where should i make ajax call to fetch dashboard data. Should i make it in navigation itself and pass it through resolve. or should i just pass the data to dashboard controller and make ajax call from there. Below is my state
$stateProvider
.state('home', {
url: '/',
templateUrl: 'templates/home.htm',
controller: 'homeController',
})
.state('dashboard', {
url: 'contact',
templateUrl: 'templates/dashboard.htm',
controller: 'dashboardController'
})
.state('state3', {
url: '/articles',
templateUrl: 'templates/state3.htm',
controller: 'state3Controller'
});
$urlRouterProvider.otherwise('/home');
This entirely depends on how you want the user experience to play out.
If you want to do all the data fetching before transitioning to the dashboard state, use a resolve state configuration
.state('dashboard', {
url: '/contact',
templateUrl: 'templates/dashboard.htm',
controller: 'dashboardController',
resolve: {
someData: function($http) {
return $http.get('something').then(res => res.data);
}
}
}
then your controller can be injected with someData, eg
.controller('dashboardController', function($scope, someData) { ... })
This will cause the state transition to wait until the someName promise has been resolved meaning the data is available right away in the controller.
If however you want to immediately transition to the dashboard state (and maybe show a loading message, spinner, etc), you would move the data fetching to the controller
.controller('dashboardController', function($scope, $http) {
$scope.loading = true; // just an example
$http.get('something').then(res => {
$scope.loading = false;
$scope.data = res.data;
});
})

Pass object through ui-router to controller

I'm creating a user profile page using angular/rails. I've set up a StateProvider using ui-router, like so,
$stateProvider
.state('friendprofile', {
url: '/{name}',
views: {
"friendProfile": {
templateUrl: '../assets/angular-app/templates/_friendProfile.html',
controller: 'friendProfileCtrl',
}
},
})
This is the click action from the template,
%a.profile{"ui-sref" => "friendprofile(user)"}
name: {{ user.name }}
Note that I'm passing user here.
So when the link .profile is clicked I go to the url http://localhost:3000/#/Jan%20Jansen. So that's working fine.
In my friendProfileCtrl I have a function that calls a service,
friendProfileService.loadProfile().then(function(response) {
$scope.user_profile = response.data;
console.log ($scope.user_profile)
})
Which calls this service,
app.factory('friendProfileService', ['$http', function($http) {
return {
loadProfile: function() {
return $http.get('/users/4.json');
}
};
}])
Currently I have the return url users/4/.json hardcoded. Can I get the users id in there somehow? Or do I have to resolve it in the StateProvider?
You could just add id parameter of user inside state so that it can be easily readable from the $stateParams.
url: '/{id}/{name}', //assuming user object has `id` property which has unique id.
So while making an ajax you could directly get the user id from the user object before making an ajax.
Controller
friendProfileService.loadProfile($stateParams.id).then(function(response) {
$scope.user_profile = response.data;
console.log ($scope.user_profile)
})
Factory
app.factory('friendProfileService', ['$http', '$stateParams', function($http) {
return {
loadProfile: function(id) {
return $http.get('/users/'+ id +'json');
}
};
}])
You've said right - you should resolve it before controller loads:
$stateProvider
.state('friendprofile', {
url: '/{name}',
views: {
"friendProfile": {
templateUrl: '../assets/angular-app/templates/_friendProfile.html',
controller: 'friendProfileCtrl',
}
},
resolve: {
user: function($stateParams, friendProfileService) {
friendProfileService.loadProfile($stateParams.name);
}
}
})
And then in the controller you can inject user variable which won't be a promise but the resolved data already:
app.controller('friendProfileCtrl', [
'$scope',
'user',
...
function($scope, user, ...) {
$scope.user_profile = user;
console.log($scope.user_profile)
}
]);
Btw the value for ui-sref should be something like that: friendprofile({name: user})
And don't forget to add input parameter to loadProfile function. Probably you should better rename {name} parameter to {id}

AngularJS UI router handling 404s

I have an app with a service which wraps my API calls:
var ConcernService = {
...
get: function (items_url, objId) {
var defer = $q.defer();
$http({method: 'GET',
url: api_url + items_url + objId}).
success(function (data, status, headers, config) {
defer.resolve(data);
}).error(function (data, status, headers, config) {
console.log('ConcernService.get status',status);
defer.reject(status);
});
return defer.promise;
},
and I'm using UI-Router to transition between states:
concernsApp
.config( function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/404/");
$stateProvider.state('project', {
url: '/project/:projectId/',
resolve: {
project: function ($stateParams, ConcernService) {
return ConcernService.get('projects/', $stateParams.projectId);
},
},
views: {
...
}
});
I'm moving from using the normal AngularJS router and I'm having difficulty understanding how to implement 404s. I can see the ConcernService throwing the console.log status as rejected, but how do I catch this in the state router?
The otherwise() rule is only invoked when no other route matches. What you really want is to intercept the $stateChangeError event, which is what gets fired when something goes wrong in a state transition (for example, a resolve failing). You can read more about that in the state change event docs.
The simplest implementation for what you're trying to do would be something like this:
$rootScope.$on('$stateChangeError', function(event) {
$state.go('404');
});
Also, since $http itself is built on promises (which resolve resolves), your ConcernService method can be simplified down to a one-liner (I realize you expanded it for debugging purposes, but you could have just as easily chained it, just FYI):
var ConcernService = {
get: function (items_url, objId) {
return $http.get(api_url + items_url + objId);
}
}
I differ between two 404 states:
Server:
show 404 page depending on server response HTTP Code 404
important to define no URL, so that user stays on URL where the error happened
Client:
URL is not found by angular ui router (none of defined URLs)
Code for Angular UI-Router state:
$stateProvider
.state('404server', {
templateUrl: '/views/layouts/404.html'
})
.state('404client', {
url: '*path',
templateUrl: '/views/layouts/404.html'
});
Code in $httpProvider interceptor:
if(response.status === 404) {
$injector.get('$state').go('404server');
}
And why I used $injector instead of $state is explained here.
You can also try something like this and see if it works for you. You may need to adjust to your needs:
.state('otherwise', {
abstract: true,
templateUrl: 'views/404.html'
})
.state('otherwise.404', {
url: '*path',
templateUrl: 'views/404.html'
})
The $urlRouterProvider only works like a $watch to $location and if the actual URL matches one of the rules defined in the .config() function then it will redirect to the specified route.
Here's what I recommend, define "/404/" as a state:
$stateProvider.state('404', {
url:'/404/',
views:{
...
}
});
And inside the reject() function move to 404 state
if(status == '404'){
$state.transitionTo('404');
}
You will have to add ui-router as dependency of the project module and use the $state provider in your controller in order to be able to use $state.transitionTo()
Here's some info: https://github.com/angular-ui/ui-router/wiki/Quick-Reference#statetransitiontoto-toparams--options
I managed to handle 404 without using $urlRoutProvider since I'm only using states by testing $state.transistion:
angular.module("app", []).run(["$state", "$rootScope", function($state, $rootScope) => {
$rootScope.$on("$locationChangeSuccess", function() {
if (!$state.transition) {
$state.go("404");
}
});
}]);
$urlRouterProvider.otherwise('/page-not-found');
.state('error', {
url: "/page-not-found",
templateUrl: "templates/error.html",
controller: "errorController"
})
Will handle your page not found problem.
If you want to raise 404 found purposefully use the state or url. We have created a separate controller just if you want to perform any operations.

reuse controllers, views and services in angular app

I want my app to fetch data from a server API, lets say I have the following API /orders , /users. Basically I just want to display the json I get from the server in a table. I am using ng-table directive for that purpose. So, in terms of components I have :
Services - both services do the same thing - go to an API and fetch JSON
Views - same view for both of the APIs, just display different data
Controllers - both fetch data from the service and display it in the table view.
So the way I see it, they all do the same thing with very minor adjustments. What I would like to do is
angular.module('admin').config(function ($routeProvider, $locationProvider) {
// same template and controller for both
$routeProvider.
when('/users', {
templateUrl: '/partials/table.html',
controllers: '/js/controllers/table.js
}).
when('/orders', {
templateUrl: '/partials/table.html',
controllers: '/js/controllers/table.js'
});
});
And in my service
factory('AdminService', ['$resource', function($resource) {
// somehow I want to inject the right endpoint, depending on the route
return $resource( '/:endpoint',
{ }, {} );
}]);
And in my table controller as well, I want to be able to know what to pass to the service
I could of course use separate controllers and services for each API endpoint it just seems like a wasteful duplication of code that does 99% the same thing
Is this possible ?
How do I wire everything together ?
If you want separate routes, but the same controller, but with some options, you can use the resolve option in the route definition to pass some options:
$routeProvider.
when('/users', {
templateUrl: '/partials/table.html',
controller: 'TableController',
resolve: {
'option1': function() {
return 'val1'
},
'option2': function() {
return 'val2'
}
}
}).
when('/orders', {
templateUrl: '/partials/table.html',
controller: 'TableController',
resolve: {
'option1': function() {
return 'val3'
},
'option2': function() {
return 'val4'
}
}
});
Then the controller in both cases will be injected with "option1" and "option2", which can be used to customise its behaviour:
app.controller('TableController', function($scope, option1, option2) {
// Do something with option1 or option1
});
From the resolve object functions, you could return a $resource object, or even return a promise that will be resolved with some data before the route is displayed. You can see the docs for $routeProvider for details.
Edit: For the resource, you could write a configurable factory like:
app.factory('MyResource', function($resource) {
return function(endpoint) {
return $resource('/' + endpoint);
}
});
And then use it in the controller:
app.controller('TableController', function($scope, MyResource, endpoint) {
var currentResource = MyResource(endpoint);
currentResource.query(); // Whatever you want to do with the $resource;
}
assuming that "endpoint" was was one of the options added in the resolve, so something like
when('/orders', {
templateUrl: '/partials/table.html',
controller: 'TableController',
resolve: {
'endpoint': function() {
return '/orders'
}

Resources