AngularJS http POST take lot of time to load data - angularjs

i have a problem in loading data take from 1 to 30 seconds to load 10000 GPS coordinates ,
after checking the server side i see server take 300ms of traitement between database query and do some traitement and send response to AngularJS side
var getItineraryVehicule_n=function (id_v,date_s,date_e) {
return $q(function (resolve,reject) {
var LOCAL_TOKEN_KEY = 'yourTokenKey';
var token= window.localStorage.getItem(LOCAL_TOKEN_KEY);
token=JSON.parse(token.split('#')[0]);
$httpBackend.whenPOST(/.*/).passThrough();
$http({
method: 'post',
dataType: 'json',
url: SERVER.url+token.response.response.user.id+'/itinerary_mongodb',
header: {
'Content-Type': 'application/json'
},
data: {
"date_s": date_s ,
"date_e": date_e,
"id_v":id_v
}
}).success(function (result) {
//console.log(JSON.stringify(result));
resolve(result);
}).error(function (err) {
console.log(err);
reject('error itinerary vehicule');
});
});
}

i have just doing that but after several times of testing I see that time in the network tab is the same in the console.log time
var getItineraryVehicule_n=function (id_v,date_s,date_e) {
var d = new Date();
return $q(function (resolve,reject) {
var LOCAL_TOKEN_KEY = 'yourTokenKey';
var token= window.localStorage.getItem(LOCAL_TOKEN_KEY);
token=JSON.parse(token.split('#')[0]);
$httpBackend.whenPOST(/.*/).passThrough();
$http({
method: 'post',
dataType: 'json',
url: SERVER.url+token.response.response.user.id+'/itinerary_mongodb',
header: {
'Content-Type': 'application/json'
},
data: {
"date_s": date_s ,
"date_e": date_e,
"id_v":id_v
}
}).success(function (result) {
console.log("in the service is take : "+(new Date().getTime()-d.getTime()));
resolve(result);
}).error(function (err) {
console.log(err);
reject('error itinerary vehicule');
});
});
}

Related

Angular: then execute before http call complete

When I call addCategory, it suppose to add my new category and then call _initAdminController() to go back to my main page and refresh the data there. But what is happening is getcourselist and getsubjectlist in initAdminController are somehow running first and then addCategory runs last. Do you know what can cause this? Am I using then correctly?
function _initAdminController() {
$scope.pageIndex = "adminTab";
console.log("reloading data");
$http({
method : 'GET',
url : 'http://testserver.com:8082/getSubjectListService'
}).then(function successCallback(response) {
$scope.updatedSubjects = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
$http({
method : 'GET',
url : 'http://testserver.hughes.com:8082/getCategoryListService'
}).then(function successCallback(response) {
$scope.categories = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
}
$scope.addCategory= function(){
var name = $scope.addCategoryData.name;
var desc = $scope.addCategoryData.description;
$http({
method : 'POST',
url : 'http://testserver.com:8082/addCategoryService',
withCredentials: true,
cache: true,
headers : { 'Content-Type': 'application/json' },
data : {
name: name,
description: desc
}
}).then(_initAdminController(), function errorCallback(response) {
console.log(response.statusText);
});
}
Also when I use then for http get, that case is working correctly. The http get finishes first and then my scope variable get updated.
And lastly before I tried the following code and in that case, successCallback doesn't run at all. So does this mean then only works for GET?
$http({
method : 'POST',
url : 'http://testserver.com:8082/addCategoryService',
withCredentials: true,
cache: true,
headers : {
'Content-Type': 'application/json'
},
data : {
name: name,
description: desc
}
}).then(
function successCallback(response) {
_initAdminController()
},
function errorCallback(response) {
console.log(response.statusText);
}
);
The code:
}).then(_initAdminController(), ...);
Should be:
}).then(_initAdminController, ...);

http request is not execute in refreshing page

my http request is not working after my token is expired in first refresh but in second refresh is work fine, but the function is executing fine what have done wrong. i work in angular frame
$http({
url: "http://localhost/ArisSystem/api/system/subsystem",
method: "GET",
dataType: 'json',
ContentType: 'application/x-www-form-urlencoded',
params: {
parentId: $scope.systemIdToLoad
},
headers: authHeaders
}).then(function (response) {
$scope.subsystem = response.data;
}), function (xhr, status, error) {
if (refreshtoken && xhr.status === 401) {
$scope.refreshlocal();
}
}
$scope.refreshlocal = function () {
$.ajax({
url: "http://localhost/ArisSystem/login",
data: {
refresh_token: refreshtoken,
grant_type: 'refresh_token'
},
type: 'POST',
dataType: 'json',
ContentType: 'application/x-www-form-urlencoded',
success: AjaxSucceeded,
error: AjaxFailed
})
function AjaxSucceeded(response) {
localStorage.setItem('accessToken', response.access_token);
localStorage.setItem('refreshToken', response.refresh_token);
refreshtoken = localStorage.getItem('refreshToken');
accesstoken = localStorage.getItem('accessToken');
authHeaders.Authorization = 'Bearer ' + accesstoken;
}
function AjaxFailed(err, response) {
window.location.href = "login.html"
}
}
You have a typo in your then function. The error-callback is outside the argument list. Instead it should be this:
$http({
...
}).then(function (response) {
$scope.subsystem = response.data;
}, function (xhr, status, error) {
if (refreshtoken && xhr.status === 401) {
$scope.refreshlocal();
}
});
I simply moved the ) from the 5th line back after the error-callback function.
That ought to do it. I'd suggest you do change the second request from $.ajax to use the $http service as well, just to keep your code consistent.

How do I refresh ng-repeat after an Angular Update

Using the code below, I am able to add items in my database, but the table showing the current entries doesn't update (I thought Angular did that automatically?) --- How do I force a refresh of the data?
.controller("addItemsController", function ($scope, $http) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('MyContacts')/items";
var vm = $scope;
var requestDigest = $("#__REQUESTDIGEST").val()
vm.addContact = function () {
return $http({
headers: { "accept": "application/json; odata=verbose", "X-RequestDigest": requestDigest, "content-Type": "application/json;odata=verbose" },
method: "POST",
url: url,
data: {
'Title': vm.LastName,
'FirstName': vm.FirstName,
"__metadata": { "type": "SP.Data.MyContactsListItem" }
}
})
.then(saveContact)
.catch(function (message) {
console.log("addContact() error: " + message);
});
function saveContact(data, status, headers, config) {
alert("Item Added Successfully");
return data.data.d;
}
}
})
NOTE: I tried using $scope.contacts.push(data) as suggested elsewhere in the forum, but contacts came back undefined (?!)

angular factory return data remained same after changing the json file

i am calling a camera.json file from "cameraData" service and injecting the cameradata service in to "CameraController". If i change the camera.json after clicked on refresh button i am getting old data. Any idea?
.factory('cameraData', function ($http, $q,globalVariable) {
var deferred = $q.defer();
var cameraData = {};
var contentType = "application/json; charset=utf-8";
cameraData.GetItemList = function(){
$('.loader').show();
var senddata ={};
senddata.installedcameraid = "9547857793457943";
$http({
//url: globalVariable.ServerAddress + "Admin_GetCameraPoints",
url: globalVariable.Camerafilepath,
dataType: 'json',
method: "POST",
data: JSON.stringify(senddata),
headers: {
"Content-Type": contentType,
"access_token": globalVariable.TOKEN
}
}).success(function(response){
//$scope.response = response;
deferred.resolve(response);
return deferred.promise;
}).error(function(error){
//$scope.error = error;
deferred.reject(error);
});
return deferred.promise;
}
return cameraData;
})
.controller('CameraController',function($scope,$timeout,cameraData){
$scope.refreshCameraData = function(){
$scope.allCamera = [];
cameraData.GetItemList()
.then(function(data) {
$scope.allCamera = data.Camera;
}, function(err) {
// promise rejected, could log the error
console.log('error', err);
});
}
cameraData.GetItemList()
.then(function(data) {
$scope.allCamera = data.Camera;
}, function(err) {
// promise rejected, could log the error
console.log('error', err);
});
})
You don't need to explicitly create a deferred object and resolve/ reject it manually. the $http() method itself returns a promise and can be directly returned as below.
.factory('cameraData', function ($http, $q,globalVariable) {
var cameraData = {};
$('.loader').show();
var contentType = "application/json; charset=utf-8";
cameraData.GetItemList = function(){
$('.loader').show();
var senddata ={};
senddata.installedcameraid = "9547857793457943";
return $http({
//url: globalVariable.ServerAddress + "Admin_GetCameraPoints",
url: globalVariable.Camerafilepath,
dataType: 'json',
method: "POST",
data: JSON.stringify(senddata),
headers: {
"Content-Type": contentType,
"access_token": globalVariable.TOKEN
}
}).then(function(response){
$('.loader').hide();
}).error(function(error){
$('.loader').hide();
});
}
return cameraData;
});
Also, for hiding the loader you can use the .finally() method as below:
return $http({
url: globalVariable.Camerafilepath,
dataType: 'json',
method: "POST",
data: JSON.stringify(senddata),
headers: {
"Content-Type": contentType,
"access_token": globalVariable.TOKEN
}
}).finally(function(response){
$('.loader').hide();
});
In your controller, you can now access the response as,
.controller('CameraController',function($scope,$timeout,cameraData){
$scope.refreshCameraData = function(){
$scope.allCamera = [];
cameraData
.GetItemList()
.then(function(response) {
$scope.allCamera = response.data.Camera;
}, function(err) {
// promise rejected, could log the error
console.log('error', err);
});
}
cameraData.GetItemList()
.then(function(response) {
$scope.allCamera = response.data.Camera;
}, function(err) {
// promise rejected, could log the error
console.log('error', err);
});
})
})
You need to create defer object everytime you call factory method. It should return new promise everytime you call api. Change your factory code with following.
var cameraData = {};
$('.loader').show();
var contentType = "application/json; charset=utf-8";
cameraData.GetItemList = function(){
// need to create defer object everytime
var deferred = $q.defer();
$('.loader').show();
var senddata ={};
senddata.installedcameraid = "9547857793457943";
$http({
//url: globalVariable.ServerAddress + "Admin_GetCameraPoints",
url: globalVariable.Camerafilepath,
dataType: 'json',
method: "POST",
data: JSON.stringify(senddata),
headers: {
"Content-Type": contentType,
"access_token": globalVariable.TOKEN
}
}).success(function(response){
//$scope.response = response;
$('.loader').hide();
deferred.resolve(response);
return deferred.promise;
}).error(function(error){
//$scope.error = error;
$('.loader').hide();
deferred.reject(error);
});
return deferred.promise;
}
return cameraData;
})

How to post on angularjs in https

here is my angularjs request whenever I submit a request it returns error and no delay.
var req = $http({
method: 'POST',
url: 'https://localhost:44300/authentication/login',
data: { UserID: Username, Password: Password },
dataType: "json"
});
req.success(
function (result) {
alert('success');
});
req.error(function (result) {
alert('something went wrong');
});
Thanks in advance.
thats how I do and it always works fine
var deferred = $q.defer();
var url = 'your url';
$http({
method: 'POST',
url: url,
data: {}
})
.then(function(data, status, headers, config) {
deferred.resolve(data);
})
.catch(function(data, status, headers, config) {
deferred.reject(msg);
});
return deferred.promise;

Resources