AngularJs response time - angularjs

I've got a factory that's fired with every request to receive the employee:
firstname;
companyid;
employeeid;
The factory looks like this:
(function()
{
angular.module('employeeApp').factory('authenticationFactory', authenticationFactory);
function authenticationFactory($cookieStore,$cookies,requestFactory,$location,GLOBALS,constants)
{
var factory = {};
factory.valid
ateUser = function()
{
var vm = this;
vm.firstname = constants.firstname;
vm.companyid = constants.companyid;
vm.companyid = constants.employeeid;
if($location.path() != '/')
{
var api_token = factory.getToken();
factory.isValidToken(api_token).then(function(response) {
if (response.status != 200) {
$location.path('/');
}
data = {"api_token": api_token};
requestFactory.post(GLOBALS.url + 'show/employee/' + $cookies.get('employeeid'), data)
.then(function (response) {
vm.firstname = response.data.result.Employee.FirstName;
vm.companyid = response.data.result.Employee.CompanyId;
vm.employeeid = response.data.result.Employee.EmployeeId;
}, function () {
$location.path('/');
});
});
}
}
When I want to show employees from a company I've got this url:
domain.com/show/employees/{companyid}
This is my controller for showing all companies:
(function()
{
angular.module('employeeApp').controller('homeController', homeController);
function homeController(employeeFactory,$cookieStore,$location,constants) {
var vm = this;
vm.employees = {};
vm.constants = constants;
vm.showEmployees = function()
{
employeeFactory.getEmployees(vm.constants.companyid)
.then(function(response)
{
vm.employees = response;
}),
function(){
$location.path('/');
};
}
vm.showEmployees();
The problem is that the response of the authenticationFactory is being fired after the homeControllerso the result is that vm.constants.companyid in my homeController is empty.
angular.js:11500 POST http://domain.dev/api/v1/show/employees/undefined 404 (Not Found)
How could I fix this?
Thankyou.

Related

angular service modal not closing properly & calling multiple times

Mentioned on the github repository #225 of angular-service-modal
But i don't have a $on on $rootScope, so that shouldn't be the problem.
(also included code below)
My modal is getting called multiple times on close/hiding. Eg. [http://beta.belgianbrewed.com/en/product/budweiser-24x30cl](Example page)
The file in question can be found on /assets/angular/controllers/ShopActionController.js
Any thoughts where the problem could be?
The code calls: showPopup(ProductId,'BuyImmediate') in ShopActionController.js
app.controller('ShopActionDialogController', ['$scope', 'CurrentProduct', function ($scope, CurrentProduct) {
$scope.CurrentProduct = CurrentProduct;
console.log("Dialog called and ...");
console.log(CurrentProduct);
//modal.element.modal();
//modal.close.then(function (result) {
// $scope.message = result ? "You said Yes" : "You said No";
//});
}]);
app.controller('ShopActionController', ['$rootScope', '$scope', '$injector', '$http', '$timeout', 'ModalService', 'EndpointService', 'ImageResizeService', 'hotkeys',
function ($rootScope, $scope, $injector, $http, $timeout, ModalService, EndpointService, ImageResizeService, hotkeys) {
$scope.Resize = ImageResizeService;
$scope.Amount;
$scope.InitAmount;
$scope.ProductId;
$scope.ProductVariantId;
$scope.OrderLineId;
$scope.isLoading = false;
$scope.isShown = true;
//$scope.addedToCart = false; //new - not implemented
$scope.inCartAmount = 0; //new - not implemented
$scope.inWishList = false;
$scope.Change = function (Amount) {
$scope.Amount += Amount;
}
$scope.showPopup = function (ProductId,action) {
EndpointService.searchProducts(undefined, 0, 1, ProductId).then(function (response) {
ModalService.showModal({
templateUrl: "ProductPopup.html",
controller: "ShopActionDialogController",
inputs: {
CurrentProduct: response.data[0]
}
}).then(function (modal) {
// The modal object has the element built, if this is a bootstrap modal
// you can call 'modal' to show it, if it's a custom modal just show or hide
// it as you need to.
// console.log("test");
modal.element.modal();
var args = {
Amount: $scope.Amount,
ProductId: response.data[0].Id,
ProductVariantId: response.data[0].ProductVariantId,
OrderLineId: undefined,
InitAmount : $scope.InitAmount
};
if (action != undefined) {
args.Action = action;
}
$rootScope.$broadcast('init', args);
$scope.Amount = $scope.InitAmount;
modal.element.on('hidden.bs.modal', function (e) {
// $scope.Amount = $scope.InitAmount;
console.log("hidden");
modal.element.remove();
// close(result, 200);
});
modal.close.then(function (result) {
// console.log("close");
$scope.Amount = $scope.InitAmount;
modal.element.remove();
// close(result, 200);
//ModalService.closeModals();
// $scope.message = result ? "You said Yes" : "You said No";
});
});
});
}
$scope.CurrentProduct;// = CurrentProduct;
$scope.initiated = false;
var initListener = $scope.$on('init', function (event,args) {
if (!$scope.initiated) {
$scope.Amount = args.Amount;
$scope.InitAmount = args.InitAmount;
$scope.ProductId = args.ProductId;
$scope.ProductVariantId = args.ProductVariantId;
$scope.OrderLineId = args.OrderLineId;
switch (args.Action)
{
case 'BuyImmediate':
$scope.AddToCart();
break;
case 'View':
break;
}
}
});
$scope.$on('$destroy', function () {
console.log("killing this scope");
initListener();
});
$scope.init = function (Amount, ProductId, ProductVariantId, OrderLineId) {
$scope.initiated = true;
$scope.Amount = Amount;
$scope.InitAmount = Amount;
$scope.ProductId = ProductId;
$scope.ProductVariantId = ProductVariantId;
$scope.OrderLineId = OrderLineId;
}
$scope.getSpecification = function (Product,SpecificationId, SpecificationName) {
var Spec = undefined;
angular.forEach(Product.Specifications, function (elem, i) {
if (elem.SpecificationCandidate.SpecificationId == SpecificationId ||
elem.SpecificationCandidate.Specification.Name == SpecificationName) {
Spec = elem.SpecificationCandidate;
}
});
return Spec;
}
$scope.isAddedInCart = function () {
return $scope.OrderLineId != undefined;
}
$scope.PriceInclusive = function (orderline) {
return orderline.Amount * orderline.Product.Price * 1.21;
}
$scope.PriceExclusive = function (orderline) {
return orderline.Amount * orderline.Product.Price;
}
$scope.bindKeys = function () {
hotkeys.add({
combo: '+',
description: 'Add 1 to ammount',
callback: function () {
$scope.Amount += 1;
}
});
hotkeys.add({
combo: '-',
description: 'Substract 1 from ammount',
callback: function () {
if ($scope.Amount > 0) {
$scope.Amount -= 1;
}
}
});
}
$scope.IncrementWith = function (Amount) {
var newAmount = $scope.Amount + Amount;
if (newAmount >= 0) {
$scope.Amount = newAmount;
}
}
$scope.ChangeSortBy = function (SortBy) {
console.log("Changing Sort By");
}
$scope.ChangePageSize = function (PageSize) {
console.log("Changing PageSize");
}
$scope.GetCart = function () {
return EndpointService.orderlines;
}
$scope.RemoveOrderLine = function ($event) {
$scope.isLoading = true;
EndpointService.removeOrderLine($scope.OrderLineId)
.then(function (response) {
EndpointService.orderlines = response.data;
$rootScope.$broadcast('DeleteOrderLine', { OrderLineId: $scope.OrderLineId });
$scope.isLoading = false;
$scope.isShown = false;
});
$event.preventDefault();
return false;
}
$scope.AddToWishlist = function () {
//AddToWishlist
EndpointService.addToWishList($scope.ProductId)
.then(function (response) {
//return true;
$scope.inWishList = true;
});
return false;
}
$scope.RemoveFromWishlist = function () {
EndpointService.removeFromWishList($scope.ProductId)
.then(function (response) {
//return true;
$scope.isShown = false;
});
return false;
}
$scope.PrepareAddOrderLineRequest = function (onlyBulk) {
if (!onlyBulk || (onlyBulk && $scope.InitAmount == 0 && $scope.InitAmount < $scope.Amount)) {
var request = EndpointService.UpdateAmountRequest;
request.OrderLineId = $scope.OrderLineId;
request.Amount = $scope.Amount;
request.ProductId = $scope.ProductId;
return request;
} else {
return undefined;
}
}
$scope.FocusAmountInput = function () {
if ($scope.Amount == $scope.InitAmount) {
$scope.Amount = "";
}
}
$scope.LeaveAmountInput = function () {
if ($scope.Amount == "") {
$scope.Amount = $scope.InitAmount;
}
}
$scope.$on("BroadCastBulkOrders", function () {
var request = $scope.PrepareAddOrderLineRequest(true);
if (request != undefined) {
$rootScope.$broadcast("AddBulkOrder", request);
$scope.Amount = $scope.InitAmount;
}
});
$scope.AddToCart = function () {
$scope.isLoading = true;
var request = $scope.PrepareAddOrderLineRequest(false);
EndpointService.updateAmount(request)
.then(function (response) {
EndpointService.orderlines = response.data;
$rootScope.$broadcast('BasketChanged');
angular.forEach(response.data, function (elem, i) {
if (elem.ProductId == $scope.ProductId) {
$scope.OrderLineId = elem.Id;
$scope.inCartAmount = elem.Amount;
}
});
$scope.Amount = $scope.InitAmount;
$scope.isLoading = false;
});
return false;
}
$scope.UpdateOrderLine = function () {
//$emit required values
$scope.isLoading = true;
var request = $scope.PrepareAddOrderLineRequest(false);
request.isFixed = true;
EndpointService.updateAmount(request)//$scope.OrderLineId, $scope.ProductId, $scope.Amount, true)
.then(function (response) {
angular.forEach(response.data, function (elem, i) {
if (elem.Id == $scope.OrderLineId) {
$rootScope.$broadcast('ChangeAmount', { OrderLineId: $scope.OrderLineId, Amount: $scope.Amount });
}
});
$scope.isLoading = false;
});
return false;
}
}]);
The service
app.service('EndpointService', ['$http', '$q', function ($http, $q) {
this.orderlines = new Array();
//search for products, standard paging included
this.searchProducts = function (searchTerm, page, pageSize, productId) {
var endPoint = "/api/Endpoint/SearchProducts?$expand=Tags,Specifications($expand=SpecificationCandidate($expand=Specification)),CoverPhoto";
if (searchTerm != undefined && searchTerm.length > 0) {
endPoint = endPoint + "&$filter=indexof(Title,'" + searchTerm + "') gt -1"; //make a var
} else if (productId !== undefined) {
{
endPoint = endPoint + "&$filter=Id eq " + productId + " "; //make a var
}
//endPoint = endPoint + "&$filter=";
}
endPoint = endPoint + "&$skip=0&$top=" + pageSize;
return $http.get(endPoint);
//.then(function (response) {
// //console.log(response.data);
// return response.data;
//})
}
// this.ShippingCost = $q.defer();
this.ShippingCost = new Object();
this.calculateShipping = function (address, shippingMethodId) {
if (address == undefined) {
return this.ShippingCost;
} else {
//https://appendto.com/2016/02/working-promises-angularjs-services/
//var deferred = $q.defer();
var endPoint = "/api/Endpoint/CalculateShippingCost?timestamp=" + Date.now();
return $http({
url: endPoint,
method: "GET",
params: {
DeliveryAddress: address,
ShippingMethodId: shippingMethodId,
timestamp: Date.now()
}
})
}
}
this.getOrderLines = function () {
var endPoint = "/api/Endpoint/GetOrder";
return $http({
url: endPoint,
method: "GET",
params: {
timestamp : Date.now()
}
})
.then(function (response) {
this.orderlines = response.data;
return this.orderlines;
});
}
this.removeOrderLine = function (OrderLineId) {
var endPoint = "/api/Endpoint/RemoveOrderLine";
return $http({
url: endPoint,
method: "POST",
params: {
OrderLineId: OrderLineId
}
});
}
this.addToWishList = function (ProductId) {
var endPoint = "/api/Endpoint/AddToWishlist";
return $http({
url: endPoint + "?ProductId=" + ProductId,
method: "GET"
});
}
this.removeFromWishList = function (ProductId) {
var endPoint = "/api/Endpoint/RemoveFromWishlist";
return $http({
url: endPoint + "?ProductId=" + ProductId,
method: "GET"
});
}
this.UpdateAmountRequest = {
ProductId: "",
Amount: 0,
OrderLineId: "",
isFixed : false
}
this.bulkUpdateAmount = function (request) {
var endPoint = "/api/Endpoint/BulkAddOrderLines";
return $http({
url: endPoint,
method: "POST",
headers: {
'Content-Type': "application/json"
},
data: request
});
}
this.updateAmount = function (request){//OrderLineId,ProductId, Amount, isFixed) {
var endPoint = "/api/Endpoint/AddOrderLine?timestamp="+ Date.now();
//console.log("hey, changing the amount " + Amount + " for product id " + ProductId + " are you? :) ");
return $http({
url: endPoint,
method: "POST",
headers: {
'Content-Type': "application/json"
},
data: request
});
}
}]);
You need to add your bootstrap modal hidden listener to the dialog controller context.
app.controller('ShopActionDialogController', ['$scope', '$element', 'CurrentProduct', 'close', function ($scope, $element, CurrentProduct, close) {
$scope.CurrentProduct = CurrentProduct;
console.log("Dialog called and ...");
console.log(CurrentProduct);
//modal.element.modal();
//modal.close.then(function (result) {
// $scope.message = result ? "You said Yes" : "You said No";
//});
//listen for when the modal is dismissed and resolve the ModalService Close promise
$element.on('hidden.bs.modal', function (e) {
close({
currentProduct: CurrentProduct
}, 200); // close, but give 200ms for bootstrap to animate
});
}]);
Note that $element and close were added to the controller dependencies.

Webservice Call using Angular in MVC

Can some one please explain how can I call an action using Angular in MVC project?
I managed to call action using Ajax like this:
var app = angular.module('toprightSec', ['ng']);
app.controller('NationalityCtrl', ['$scope', function ($scope, $http) {
$scope.items = [];
var items = populateListFromLocalStorage("offices", "Login/GetOffices", 24);
var officelist = "";
for (var i = 0; i < items.length; i++)
{
$scope.items[i] = { "name": read_prop(items[i], 'office_desc'), "guid": read_prop(items[i], 'office_guid') };
}
$scope.reloadPage = function () { window.location.reload(); }
$scope.getResult = function ($index, item) {
$.ajax({
type: 'GET',
async: true,
url: 'Login/ChangeOffice',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
officeID: $scope.items[$index].guid,
officeName: $scope.items[$index].name,
},
success: function (msg) {
}
});
};
}]);
I tried changing it to Angular like this:
var AngularModule = angular.module('toprightSec', ['ng']);
AngularModule.service('ApiCall', ['http', function ($http) {
var result;
this.PostApiCall = function (controllerName, methodName, obj) {
debugger;
result = $http.post('api/' + controllerName + '/' + methodName,obj).success(function (data, success) {
result = (data);
}).error(function () {
("Something went wrong");
});
return result;
};
}]);
AngularModule.controller('NationalityCtrl', ['$scope', function ($scope, $http, ApiCall) {
$scope.items = [];
var items = populateListFromLocalStorage("offices", "Login/GetOffices", 24);
var officelist = "";
for (var i = 0; i < items.length; i++)
{
$scope.items[i] = { "name": read_prop(items[i], 'office_desc'), "guid": read_prop(items[i], 'office_guid') };
}
$scope.reloadPage = function () { window.location.reload(); }
$scope.getResult = function ($index, item) {
var obj = {
'officeID' : '123',
'officeName' : 'Sample'
}
var result = ApiCall.PostApiCall("Login", "ChangeOffice", obj).success(function (data) {
var data = $.parseJSON(JSON.parse(data));
$scope.message = data;
});
};
}]);
I keep getting this error "PostApiCall" is not defined on browser console.
Any idea what am I doing wrong here?
Thanks.
User promise, return when $http are done:
this.PostApiCall = function (controllerName, methodName, obj) {
debugger;
var deferred = $q.defer();
$http.post('api/' + controllerName + '/' + methodName,obj).success(function (data) {
deferred.resolve(data);
});
return deferred.promise;
};
var result = ApiCall.PostApiCall("Login", "ChangeOffice", obj).then(function (data) {
var data = $.parseJSON(JSON.parse(data));
$scope.message = data;
});
Well, I managed to fix it, I noticed two issues with my code:
I was using $http in two different places, and I was using success at both the spots. (solution suggested by charlietfl)
The other issue was that the parameters that I was passing, they were not right.
This is my updated working code:
var app = angular.module('BMSApp', []);
app.factory('ApiCall', ['$http', function ($http) {
var PostApiCall = function (controllerName, methodName) {
return $http.post(controllerName + '/' + methodName);
};
var GetApiCall = function (controllerName, methodName) {
return $http.get(controllerName + '/' + methodName);
};
return {
PostApiCall: PostApiCall,
GetApiCall: GetApiCall
};
}]);
app.controller('NationalityCtrl', ['ApiCall', '$scope', function (ApiCall,$scope) {
$scope.items = [];
var items = populateListFromLocalStorage("offices", "Login/GetOffices", 24);
var officelist = "";
for (var i = 0; i < items.length; i++)
{
$scope.items[i] = { "name": read_prop(items[i], 'office_desc'), "guid": read_prop(items[i], 'office_guid') };
}
$scope.getResult = function ($index, item) {
var result = ApiCall.PostApiCall("Login", "ChangeOffice/?officeID=" + $scope.items[$index].guid + "&officeName="+$scope.items[$index].name).then(function (data) {
$scope.reloadPage();
});
};
}]);
Thanks everyone for the help.

How to Use Factory Service in AngularJS?

I found this service (see below) on GitHub and want to know how to use this service on > click of button. I am using this in my Ionic app for log in using Google+ OAuth.
I am new to AngularJS. Help me.
var googleLoginService = angular.module('GoogleLoginService', ['ngStorage']);
googleLoginService.factory('timeStorage', ['$localStorage', function ($localStorage) {
var timeStorage = {};
timeStorage.cleanUp = function () {
var cur_time = new Date().getTime();
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
if (key.indexOf('_expire') === -1) {
var new_key = key + "_expire";
var value = localStorage.getItem(new_key);
if (value && cur_time > value) {
localStorage.removeItem(key);
localStorage.removeItem(new_key);
}
}
}
};
timeStorage.remove = function (key) {
this.cleanUp();
var time_key = key + '_expire';
$localStorage[key] = false;
$localStorage[time_key] = false;
};
timeStorage.set = function (key, data, hours) {
this.cleanUp();
$localStorage[key] = data;
var time_key = key + '_expire';
var time = new Date().getTime();
time = time + (hours * 1 * 60 * 60 * 1000);
$localStorage[time_key] = time;
};
timeStorage.get = function (key) {
this.cleanUp();
var time_key = key + "_expire";
if (!$localStorage[time_key]) {
return false;
}
var expire = $localStorage[time_key] * 1;
if (new Date().getTime() > expire) {
$localStorage[key] = null;
$localStorage[time_key] = null;
return false;
}
return $localStorage[key];
};
return timeStorage;
}]);
googleLoginService.factory('googleLogin', [
'$http', '$q', '$interval', '$log', 'timeStorage',
function ($http, $q, $interval, $log, timeStorage) {
var service = {};
service.access_token = false;
service.redirect_url = 'http://127.0.0.1:81/google_demo/www/';
service.client_id = '1234567890';
service.secret = 'xxxxxxxxxxxxxxxxx';
service.scope = 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/plus.me';
service.gulp = function (url, name) {
url = url.substring(url.indexOf('?') + 1, url.length);
return url.replace('code=', '');
};
service.authorize = function (options) {
var def = $q.defer();
var self = this;
var access_token = timeStorage.get('google_access_token');
if (access_token) {
$log.info('Direct Access Token :' + access_token);
service.getUserInfo(access_token, def);
} else {
var params = 'client_id=' + encodeURIComponent(options.client_id);
params += '&redirect_uri=' + encodeURIComponent(options.redirect_uri);
params += '&response_type=code';
params += '&scope=' + encodeURIComponent(options.scope);
var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + params;
var win = window.open(authUrl, '_blank', 'location=no,toolbar=no,width=800, height=800');
var context = this;
if (ionic.Platform.isWebView()) {
console.log('using in app browser');
win.addEventListener('loadstart', function (data) {
console.log('load start');
if (data.url.indexOf(context.redirect_url) === 0) {
console.log('redirect url found ' + context.redirect_url);
console.log('window url found ' + data.url);
win.close();
var url = data.url;
var access_code = context.gulp(url, 'code');
if (access_code) {
context.validateToken(access_code, def);
} else {
def.reject({error: 'Access Code Not Found'});
}
}
});
} else {
console.log('InAppBrowser not found11');
var pollTimer = $interval(function () {
try {
console.log("google window url " + win.document.URL);
if (win.document.URL.indexOf(context.redirect_url) === 0) {
console.log('redirect url found');
win.close();
$interval.cancel(pollTimer);
pollTimer = false;
var url = win.document.URL;
$log.debug('Final URL ' + url);
var access_code = context.gulp(url, 'code');
if (access_code) {
$log.info('Access Code: ' + access_code);
context.validateToken(access_code, def);
} else {
def.reject({error: 'Access Code Not Found'});
}
}
} catch (e) {
}
}, 100);
}
}
return def.promise;
};
service.validateToken = function (token, def) {
$log.info('Code: ' + token);
var http = $http({
url: 'https://www.googleapis.com/oauth2/v3/token',
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
params: {
code: token,
client_id: this.client_id,
client_secret: this.secret,
redirect_uri: this.redirect_url,
grant_type: 'authorization_code',
scope: ''
}
});
var context = this;
http.then(function (data) {
$log.debug(data);
var access_token = data.data.access_token;
var expires_in = data.data.expires_in;
expires_in = expires_in * 1 / (60 * 60);
timeStorage.set('google_access_token', access_token, expires_in);
if (access_token) {
$log.info('Access Token :' + access_token);
context.getUserInfo(access_token, def);
} else {
def.reject({error: 'Access Token Not Found'});
}
});
};
service.getUserInfo = function (access_token, def) {
var http = $http({
url: 'https://www.googleapis.com/oauth2/v3/userinfo',
method: 'GET',
params: {
access_token: access_token
}
});
http.then(function (data) {
$log.debug(data);
var user_data = data.data;
var user = {
name: user_data.name,
gender: user_data.gender,
email: user_data.email,
google_id: user_data.sub,
picture: user_data.picture,
profile: user_data.profile
};
def.resolve(user);
});
};
service.getUserFriends = function () {
var access_token = this.access_token;
var http = $http({
url: 'https://www.googleapis.com/plus/v1/people/me/people/visible',
method: 'GET',
params: {
access_token: access_token
}
});
http.then(function (data) {
console.log(data);
});
};
service.startLogin = function () {
var def = $q.defer();
var promise = this.authorize({
client_id: this.client_id,
client_secret: this.secret,
redirect_uri: this.redirect_url,
scope: this.scope
});
promise.then(function (data) {
def.resolve(data);
}, function (data) {
$log.error(data);
def.reject(data.error);
});
return def.promise;
};
return service;
}
]);
angular
.module('GoogleLoginService')
.controller('SomeController', SomeController);
function SomeController(timeStorage, googleLogin) {
// just call timeStorage and googleLogin
// ex:
var anydata = timeStorage.get("anykey");
}

data from one angular call method to another method as parameter

The following is the code structure, iam using hot towel template for mvc project.
The script:
(function () {
'use strict';
var controllerId = 'EditEmployeeController';
angular.module('app').controller(controllerId, ['common', 'EmployeeService', EmployeeData]);
function EmployeeData(common, EmployeeService) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var $filter = common.$filter;
var logError = common.logger.getLogFn('app', 'error');
var vm = this;
vm.CountryCode;
vm.Country = [];
vm.State = [];
vm.employeeInfo = {};
//calling the method to get the Employee info
activate();
//calling the methods to get the States
GetStates();
function activate() {
var promises = [GetEmployeeInfo(),GetStates()];
common.activateController(promises, controllerId)
.then(function () { });
}
}
function GetEmployeeInfo() {
return EmployeeService.getEmpInfoForEdit(personId).then(function (data) {
vm.CountryCode = data.Country;
return vm.employeeInfo = data;
}
function GetStates() {
return EmployeeService.getStates(vm.CountryCode).then(function (data) {
return vm.State = data;
}
}
})();
EmployeeService.js
code snippet from EmployeeService.js
function getEmpInfoForEdit(personId) {
var EmpInfoForEdit = $resource('Employee/GetEmployeeDetailsForEdit', angular.fromJson(personId), { 'query': { method: 'POST', isArray: false } });
var deferred = $q.defer();
EmpInfoForEdit.query({}, function (response) {
deferred.resolve(response);
}, function (error) {
deferred.reject(error);
})
return deferred.promise;
}
vm.CountryCode always shows null, though we are assigning a value to it in the GetEmployeeInfo method.Because unable to get the states.
please let me know can we get the data into vm.CountryCode ?
(function () {
'use strict';
var controllerId = 'EditEmployeeController';
angular.module('app').controller(controllerId, ['common', 'EmployeeService', EmployeeData]);
function EmployeeData(common, EmployeeService) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var $filter = common.$filter;
var logError = common.logger.getLogFn('app', 'error');
var vm = this;
vm.CountryCode=[];
vm.Country = [];
vm.State = [];
vm.employeeInfo = {};
//calling the method to get the Employee info
activate();
//calling the methods to get the States
GetStates();
function activate() {
var promises = [GetEmployeeInfo(),GetStates()];
common.activateController(promises, controllerId)
.then(function () { });
}
}
function GetEmployeeInfo() {
return EmployeeService.getEmpInfoForEdit(personId).then(function (data) {
vm.CountryCode = data.Country;
return vm.employeeInfo = data;
}
function GetStates() {
return EmployeeService.getStates(vm.CountryCode).then(function (data) {
return vm.State = data;
}
}
})();
If you want to work with the EmployeeService.getEmpInfoForEdit and EmployeeService.getStates returned data, you should inject $q in your controller and use the resolve data as the following example :
angular.module('app').controller(controllerId, ['$q', 'common', 'EmployeeService', EmployeeData]);
...
function GetEmployeeInfo() {
var deferred = $q.defer();
return EmployeeService.getEmpInfoForEdit(personId).then(function (data) {
deferred.resolve(data);
}
}
function GetStates() {
var deferred = $q.defer();
return EmployeeService.getStates(vm.CountryCode).then(function (data) {
deferred.resolve(data);
}
}
the issue is resolved by moving the GetStates method inside the then
var promises = [GetEmployeeInfo(),GetStates()];
common.activateController(promises, controllerId)
.then(function () { });
}
}
changed to
var promises = [GetEmployeeInfo()];
common.activateController(promises, controllerId)
.then(function () { GetStates() });
}
}

Storing tokens with OAuth 2.0 in Angular

I have an app which displays Google Calendar data, but it requires an initial login. I know it's possible to store tokens using OAuth 2.0, but I'm not sure how to go about doing it. Here is my code below. I'd like for the webpage to display the a calendar using JSON data from a google calendar without login.
Controller
angular.module('demo', ["googleApi"])
.config(function(googleLoginProvider) {
googleLoginProvider.configure({
clientId: '239511214798.apps.googleusercontent.com',
scopes: ["https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/plus.login"]
});
})
.controller('DemoCtrl', ['$scope', 'googleLogin', 'googleCalendar', 'googlePlus', function ($scope, googleLogin, googleCalendar, googlePlus) {
$scope.login = function () {
googleLogin.login();
};
$scope.$on("googlePlus:loaded", function() {
googlePlus.getCurrentUser().then(function(user) {
$scope.currentUser = user;
});
})
$scope.currentUser = googleLogin.currentUser;
$scope.loadEvents = function() {
this.calendarItems = googleCalendar.listEvents({calendarId: this.selectedCalendar.id});
}
$scope.loadCalendars = function() {
$scope.calendars = googleCalendar.listCalendars();
}
}]);
googleAPi
angular.module('googleApi', [])
.value('version', '0.1')
.service("googleApiBuilder", function($q) {
this.loadClientCallbacks = [];
this.build = function(requestBuilder, responseTransformer) {
return function(args) {
var deferred = $q.defer();
var response;
request = requestBuilder(args);
request.execute(function(resp, raw) {
if(resp.error) {
deferred.reject(resp.error);
} else {
response = responseTransformer ? responseTransformer(resp) : resp;
deferred.resolve(response);
}
});
return deferred.promise;
}
};
this.afterClientLoaded = function(callback) {
this.loadClientCallbacks.push(callback);
};
this.runClientLoadedCallbacks = function() {
for(var i=0; i < this.loadClientCallbacks.length; i++) {
this.loadClientCallbacks[i]();
}
};
})
.provider('googleLogin', function() {
this.configure = function(conf) {
this.config = conf;
};
this.$get = function ($q, googleApiBuilder, $rootScope) {
var config = this.config;
var deferred = $q.defer();
return {
login: function () {
gapi.auth.authorize({ client_id: config.clientId, scope: config.scopes, immediate: false}, this.handleAuthResult);
return deferred.promise;
},
handleClientLoad: function () {
gapi.auth.init(function () { });
window.setTimeout(checkAuth, 1);
},
checkAuth: function() {
gapi.auth.authorize({ client_id: config.clientId, scope: config.scopes, immediate: true }, this.handleAuthResult );
},
handleAuthResult: function(authResult) {
if (authResult && !authResult.error) {
var data = {};
$rootScope.$broadcast("google:authenticated", authResult);
googleApiBuilder.runClientLoadedCallbacks();
deferred.resolve(data);
} else {
deferred.reject(authResult.error);
}
},
}
};
})
.service("googleCalendar", function(googleApiBuilder, $rootScope) {
var self = this;
var itemExtractor = function(resp) { return resp.items; };
googleApiBuilder.afterClientLoaded(function() {
gapi.client.load('calendar', 'v3', function() {
self.listEvents = googleApiBuilder.build(gapi.client.calendar.events.list, itemExtractor);
self.listCalendars = googleApiBuilder.build(gapi.client.calendar.calendarList.list, itemExtractor);
self.createEvent = googleApiBuilder.build(gapi.client.calendar.events.insert);
$rootScope.$broadcast("googleCalendar:loaded")
});
});
})
.service("googlePlus", function(googleApiBuilder, $rootScope) {
var self = this;
var itemExtractor = function(resp) { return resp.items; };
googleApiBuilder.afterClientLoaded(function() {
gapi.client.load('plus', 'v1', function() {
self.getPeople = googleApiBuilder.build(gapi.client.plus.people.get);
self.getCurrentUser = function() {
return self.getPeople({userId: "me"});
}
$rootScope.$broadcast("googlePlus:loaded")
});
});
})
What you will want to do is after the result comes back you will want to save it off to localStorage or a cookie and then use that in the future if it exists.
Essentially you will need to update your handleAuthResult to store the result from the Google API:
handleAuthResult: function (authResult) {
if (authResult && !authResult.error) {
var data = {};
$rootScope.$broadcast("google:authenticated", authResult);
googleApiBuilder.runClientLoadedCallbacks();
// here you will store the auth_token
window.localStorage.setItem('auth_token', authResult.token /*I don't know what this response looks like, but it should be similar to this*/ );
deferred.resolve(data);
} else {
deferred.reject(authResult.error);
}
},
Live Demo

Resources