AngularJS: Call a particular function before any partial page controllers - javascript

I want to call a particular function: GetSession() at the beginning of my application load. This function makes a $http call and get a session token: GlobalSessionToken from the server. This session token is then used in other controllers logic and fetch data from the server. I have call this GetSession()in main controller: MasterController in $routeChangeStart event but as its an asynchronous call, my code moves ahead to CustomerController before the $http response.
Here is my code:
var GlobalSessionToken = ''; //will get from server later
//Define an angular module for our app
var myApp = angular.module('myApp', ['ngRoute']);
//Define Routing for app
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/customer', {
templateUrl: 'partials/customer.html',
controller: 'CustomerController',
resolve: {
loadData: function($q){
return LoadData2($q,'home');
}
}
}).
otherwise({
redirectTo: '/home'
});
}]);
//controllers start here and are defined in their each JS file
var controllers = {};
//only master controller is defined in app.js, rest are in separate js files
controllers.MasterController = function($rootScope, $http){
$rootScope.$on('$routeChangeStart', function(){
if(GlobalSessionToken == ''){
GetSession();
}
console.log('START');
$rootScope.loadingView = true;
});
$rootScope.$on('$routeChangeError', function(){
console.log('ERROR');
$rootScope.loadingView = false;
});
};
controllers.CustomerController = function ($scope) {
if(GlobalSessionToken != ''){
//do something
}
}
//adding the controllers to myApp angularjs app
myApp.controller(controllers);
//controllers end here
function GetSession(){
$http({
url: GetSessionTokenWebMethod,
method: "POST",
data: "{}",
headers: { 'Content-Type': 'application/json' }
}).success(function (data, status, headers, config) {
GlobalSessionToken = data;
}).error(function (data, status, headers, config) {
console.log(data);
});
}
And my HTML has following sections:
<body ng-app="myApp" ng-controller="MasterController">
<!--Placeholder for views-->
<div ng-view="">
</div>
</body>
How can I make sure this GetSession() is always called at the very beginning of my application start and before any other controller calls and also called only once.
EDIT: This is how I added run method as per Maxim's answer. Still need to figure out a way to wait till $http call returns before going ahead with controllers.
//Some initializing code before Angular invokes controllers
myApp.run(['$rootScope','$http', '$q', function($rootScope, $http, $q) {
return GetSession($http, $q);
}]);
function GetSession($http, $q){
var defer = $q.defer();
$http({
url: GetSessionTokenWebMethod,
method: "POST",
data: "{}",
headers: { 'Content-Type': 'application/json' }
}).success(function (data, status, headers, config) {
GlobalSessionToken = data;
defer.resolve('done');
}).error(function (data, status, headers, config) {
console.log(data);
defer.reject();
});
return defer.promise;
}

Even though some of the solutions here are perfectly valid, resolve property of the routes definition is the way to go, in my opinion. Writing your app logic inside session.then in every controller is a bit too much , we're used such approach too in one of the projects and I didn't work so well.
The most effective way is to delay controller's instantiation with resolve, as it's a built-in solution. The only problem is that you have to add resolve property with similar code for every route definition, which leads to code duplication.
To solve this problem, you can modify your route definition objects in a helper function like this:
function withSession(routeConfig) {
routeConfig.resolve = routeConfig.resolve || {};
routeConfig.resolve.session = ['getSessionPromise', function(getSessionPromise) {
return getSessionPromise();
}]
return routeConfig;
}
And then, where define your routes like this:
$routeProvider.when('/example', withSession({
templateUrl: 'views/example.html',
controller: 'ExampleCtrl'
}));
This is one of the many solutions I've tried and liked the most since it's clean and DRY.

You can't postpone the initialisation of controllers.
You may put your controller code inside a Session promise callback:
myApp.factory( 'session', function GetSession($http, $q){
var defer = $q.defer();
$http({
url: GetSessionTokenWebMethod,
method: "POST",
data: "{}",
headers: { 'Content-Type': 'application/json' }
}).success(function (data, status, headers, config) {
GlobalSessionToken = data;
defer.resolve('done');
}).error(function (data, status, headers, config) {
console.log(data);
defer.reject();
});
return defer.promise;
} );
myApp.controller( 'ctrl', function($scope,session) {
session.then( function() {
//$scope.whatever ...
} );
} );
Alternative: If you don't want to use such callbacks, you could have your session request synchronous, but that would be a terrible thing to do.

You have not provided any details related to GetSession. For scenarios like this you should use the resolve property while defining your routes in $routeProvider. I see you are using resolve already.
What you can do now is to wrap the GlobalSessionToken into a Angular service like GlobalSessionTokenServiceand call it in the resolve to get the token before the route loads. Like
resolve: {
loadData: function($q){
return LoadData2($q,'home');
},
GlobalSessionToken: function(GlobalSessionTokenService) {
return GlobalSessionTokenService.getToken() //This should return promise
}
}
This can then be injected in your controller with
controllers.MasterController = function($rootScope, $http,GlobalSessionToken){

Related

Passing information previously retrieved to templateProvider in AngularJS

I'm using AngularJS 1.3 and UI-Router. I have an state in which i have a resolve and a templateProvider.
What i'm trying to accomplish is that the information retrieved from database in the resolve can be used by the templateProvider. Right now, I have to get the information twice, once from resolve and another from templateProvider, and that's annoying.
The code:
.state('articleurl', {
url: '/:articleUrl',
resolve: {
article: function ($http, $stateParams, $location) {
return $http({
method: 'GET',
url: '/articles/' + $stateParams.articleUrl
})
.then(function (article) {
return article;
}, function (error) {
$location.path('/404');
});
},
loggedin: checkLoggedin
},
templateProvider: ['$templateFactory', '$stateParams', '$http', function ($templateFactory, $stateParams, $http) {
return $http({
method: 'GET',
url: '/articles/' + $stateParams.articleUrl
}).then(function(article) {
if ( article.data.template )
return $templateFactory.fromUrl('articles/views/templates/' + article.data.template + '.html');
else
return $templateFactory.fromUrl('articles/views/templates/news.html');
});
}],
controller: 'ArticlesViewController'
})
As you can see, according to article's kind i load a different template in the templateProvider. Besides, i use the article's information in the controller which has been previously got in the state's resolve.
Is there any way to use in the templateProvider the information previously fetched in the resolve avoiding this way another call to database?
Right now, it is doing 2 calls to database per connection...
Thanks!
app.factory('article', function ($cacheFactory){
var articleCache = $cacheFactory('article');
return function (url) {
return articleCache.get(url) || articleCache.put(url, $http({
method: 'GET',
url: '/articles/' + url
})
);
};
});
Use it as article($stateParams.articleUrl).then(...) in both places, that will keep the things DRY. You may get better control over the cache (e.g. expiration) by replacing $cacheFactory with angular-cache.
$http own caching may be successfully used as well instead of explicit caching:
If there are multiple GET requests for the same URL that should be
cached using the same cache, but the cache is not populated yet, only
one request to the server will be made and the remaining requests will
be fulfilled using the response from the first request.
I think you can inject directly the resolved variables, so you could inject article in templateProvider:
.state('articleurl', {
url: '/:articleUrl',
resolve: {
article: function ($http, $stateParams, $location) {
return $http({
method: 'GET',
url: '/articles/' + $stateParams.articleUrl
})
.then(function (article) {
return article;
}, function (error) {
$location.path('/404');
});
},
loggedin: checkLoggedin
},
templateProvider: ['$templateFactory', '$stateParams', '$http', 'article', function ($templateFactory, $stateParams, $http, article) {
// Now here you can use article without the need to re-call it
}],
controller: 'ArticlesViewController'
})

Defer execution of page controller until init data is gathered

I have an SPA. I have some basic init data that I'm fetching from the server that I'm certain that I want to defer every page load until that data is loaded. (this data contains whether the user is logged in, permissions, and other vital stuff). So if I have a service for fetching and accessing that data, a page controller might start execution before I have the data, which is bad.
I can't use a promise either, partly because it doesn't solve my problem that I don't want the page to begin loading, and partly because it can't be updated easily and I don't want to always use a promise to fetch this basic data
this is what i've tried so far:
my service
app.factory('AppData', function($q, $http){
var appData = {};
$http
.post( "/api/GeneralActions/getInitData", {
}).success(function (data, status, headers, config) {
appData = data;
}).error(function (data, status, headers, config) {
});
return {
getAppData: function () {
return appData;
}
};
});
my page controller:
app.controller('MainPreferences', function($scope, AppData){
// when this gets executed, appData is null
$scope.appData = AppData.getAppData();
});
Try following snippet
app.factory('AppData', function($q, $http){
var appData = {};
$http
.post( "/api/GeneralActions/getInitData", {
}).success(function (data, status, headers, config) {
//appData = data;
angular.extend(appData, data);
}).error(function (data, status, headers, config) {
});
return {
getAppData: function () {
return appData;
}
};
});
Instead creating appData object again, just extend it with data . By this way your appData object pointer will not change and controllers will also get updated.
Are you using ngRoute? If so, it sounds like what you want is to have a resolve property on your routes to require them to load something before changing the path to the new route.
See the ngRoute docs and search for resolve.
If you are using the stock Angular ngRoute routing system, you can use the resolve property on the route to specify a map of promise-returning functions. The route controller will not be initialized before these promises are all resolved, and as a bonus, the promises' results are injected into the route controller.
For example:
$routeProvider.when('/foo', {
controller: 'fooCtrl',
resolve: {
bar: function($http) { return $http.get('/load/the/bar'); }
}
});
// bar is injected from the route resolve
myApp.controller('fooCtrl', function($scope, bar) {
$scope.bar = bar;
});
I think it should be:
app.factory('AppData', function($q, $http){
var appData = {};
return {
getAppData: function () {
$http.post( "/api/GeneralActions/getInitData", {}).success(function (data, status, headers, config) {
return data;
}).error(function (data, status, headers, config) {
});
}
};
});

How can I gain access to a Javascript variable from within a return function?

function storyData($http, $q) {
var URL = 'stories.json';
var storyCache = [];
this.getStories = function() {
var deferred = $q.defer();
alert(URL);
$http({method: 'GET', url: URL})
.success(function (data, status, headers, config) {
storyCache = data;
alert(storyCache); //correct data appears in the alert window, but this doesn't set the instance storyCache variable for some reason
deferred.resolve(data);
})
.error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
};
this.stories = function() {
return storyCache;
}
}
My app -
'use strict';
var angularApp = angular.module('ccsApp', ['ngRoute', 'ngAnimate', 'ui.bootstrap']);
angularApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'stories.html',
controller: 'StoryController as StoryCtrl',
resolve: {
stories: function(storyData) {
return storyData.getStories();
}
}
})
.otherwise({
redirectTo: '/'
});
}
]);
Within my controller, I'm not injecting the "stories" value from the routeProvider so that I can use my service.
Why am I unable to change storyCache from within my $http method? I'm confident this is something terribly simple, but my research hasn't led me to an answer. Thank you in advance for your help.
The async. aspect of this works fine and is not the problem. I'm ensuring that I have the data by using the resolve object on my routeProvider. Also, I'm ensuring that I have the data before the deferred.resolve(data) method executes by issuing an alert on it. I don't have the solution, but an error in my use of async. is not the solution either.

AngularJS UI Not updating after $.ajax Success

I'm new to AngularJS and I'm trying to modify the example at http://www.codeproject.com/Articles/576246/A-Shopping-Cart-Application-Built-with-AngularJS
I've implemented a new payment service in the example to call a Json method on my server which works fine, but when I call the method clearItems(); to remove the items from the cart on success it removes the items as expected in the background (as I can see from refreshing the page and the cart it empty) - my problem is that it does not clear the cart in the UI (without refreshing)
If I call this.clearItems(); after the Json call it clears the cart items in the UI as expected, but this is not what I requiquire as I only want to clear the items after success.
Can anyone suggest how I can get this to work?
My Json call is listed below
var me = this;
//this.clearCart = clearCart == null || clearCart;
$.ajax({
cache: false,
type: "POST",
url: '/pos/JsonCashPayment',
contentType: 'application/json',
dataType: "json",
data: JSON.stringify(this.items),
success: function (data) {
me.clearItems();
alert('success function called');
// Do something with the returned data
// This can be any data
}
});
//this.clearItems();
Thanks
Mark
EDIT - Problems running $http
Further to the advice form marck I understand that to do this I need to use $http instead of $json. The problem with doing this is that I need to do this in the shoppingCart.js class (as part of the payments section) which is attached to the controller via app.js (code below). When I try this though I get a JS error that $http doesn't exist.
Is there a way to use $http from the shoppingCart.js class?
app.js
var storeApp = angular.module('AngularStore', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/store', {
templateUrl: 'POS/store',
controller: storeController
}).
when('/products/:productSku', {
templateUrl: 'POS/product',
controller: storeController
}).
when('/cart', {
templateUrl: 'POS/shoppingCart',
controller: storeController
}).
otherwise({
redirectTo: '/store'
});
}]);
// create a data service that provides a store and a shopping cart that
// will be shared by all views (instead of creating fresh ones for each view).
storeApp.factory("DataService", function ($http) {
// create store
var myStore = new store($http);
// create shopping cart
var myCart = new shoppingCart("AngularStore");
controller.js
function storeController($scope, $http, $routeParams, DataService) {
// get store and cart from service
$scope.store = DataService.store;
$scope.cart = DataService.cart;
shoppingCart.js
function shoppingCart(cartName) {
this.cartName = cartName;
this.clearCart = false;
this.checkoutParameters = {};
this.items = [];
// load items from local storage when initializing
this.loadItems();
// save items to local storage when unloading
var self = this;
$(window).unload(function () {
if (self.clearCart) {
self.clearItems();
}
self.saveItems();
self.clearCart = false;
});
}
shoppingCart.prototype.checkoutCash = function (parms, clearCart, $scope, $http) {
// Need to be able to run $http here
$http({
url: '/pos/JsonCashPayment',
method: "POST",
data: this.items,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (data, status, headers, config) {
}).error(function (data, status, headers, config) {
});
}
To make your approach work, you need to inject $http into your controller, then pass it further to the function you've defined in shoppingcart.js, like so in controller.js:
'use strict';
// the storeController contains two objects:
// - store: contains the product list
// - cart: the shopping cart object
function storeController($scope, $routeParams, DataService, $http) {
// get store and cart from service
$scope.store = DataService.store;
$scope.cart = DataService.cart;
// use routing to pick the selected product
if ($routeParams.productSku != null) {
$scope.product = $scope.store.getProduct($routeParams.productSku);
}
$scope.cart.checkoutCash('parms', 'clearCart', $scope, $http);
}
Obviously, the first two arguments I sent to checkoutCash are filler and need to be replaced with more appropriate values.

AngularJS - $q's Promise not cascading to controller properly

While I'm reading up on Pluralsight's fundamentals on AngularJS, I'm stumped with my $http + $q.defer() not working as it should be. It seems like even the deferred variable has been resolved, the change still doesn't cascade onto the controller.
My View:
<li class="row" ng-repeat="item in jsonData.Items">
My Service:
mediaApp.factory('ServiceData', function ($http,$q) {
return{
getJson: function ($scope) {
var deferred = $q.defer();
$http(
{
method: 'GET',
url: url
}).
success(function (data, status, header, config) {
$timeout(function () {
deferred.resolve(data);
});
})
}
My Controller:
$scope.jsonData = ServiceData.getJson($scope);
Meanwhile, these lines of code work on the controller:
ServiceData.getJson($scope).
then(function (data) {
$scope.jsonData = data;
});
Can someone enlighten me on this? I believe the workaround is already proper, but I would like to understand why certain implementations of the code doesn't work as expected.
What gives?
You aren't returning the promise from getJson
mediaApp.factory('ServiceData', function ($http, $q) {
return {
getJson: function ($scope) {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'json.json'
}).
success(function (data, status, header, config) {
deferred.resolve(data);
})
/* return the promise*/
return deferred.promise
}
}
})
Since $http returns a promise....you could to the same thing without creating your own deffered and just return the $http call
DEMO

Categories

Resources