How to store http angularjs call response to variable - angularjs

I'm making http get call from angularJS function. Call works perfectly and get the response back but I need to store response in a variable so I can use it outside of $http. I tried to keep in $scope.data.submissionFileID but alert($scope.data.submissionFileID) says undefined. Also I want me make this call synchronous. I'm new to this, can you please help to modify this below code?
$scope.openWindow = function (e) {
var url = '/Submission/GetSubmissionFileInfo?' + 'id=' + SubmissionID;
$http.get(url).success(function (response) {
$scope.data.submissionFileID = response; // response is an integer such as 123
});
alert($scope.data.submissionFileID); // This is undefined, what should I do to fix it?
var content = "<h7><b>" + "Created at </b>" + $scope.data.submissionFileID + "</h7><br><br>";
}

Something to consider is that the alert(...) is being called before the async function has a chance to complete. An option would be to send the response off to another function that sets the $scope variable and does whatever else you might want.
$scope.openWindow = function (e) {
var url = '/Submission/GetSubmissionFileInfo?' + 'id=' + SubmissionID;
$http.get(url).success(function (response) {
$scope.doTheThing(response);
});
}
$scope.data = {}
$scope.doTheThing = function(response) {
$scope.data.submissionFileID = response;
}
in the HTML template file...
<div ng-if="!data.submissionFileID">Retrieving Data....</div>
<div ng-if="data.submissionFileID">
<h7><b>Created at </b> {{data.submissionFileID}}</h7>
</div>

Related

http.get with params send word query

This is my first question, excuse my english.
I'm working with angular and I'm using http.post for all (get and post info). And how this is wrong, I'd start to use http.get for request the record from Database.
I'm using this:
$http.get("empresa.php",{params:{id:-1,action:"get"}})
I expect receive something like this:
empresa.php?id=-1&action=get
But not work, because send this:
empresa.php?query=%7B%22id%22:-1,%22action%22:%22get%22%7D
Could you help me?
query is not so I'expect to be.
I'm using Angularjs 1.5.8
EDITION
Te factory is this:
app.factory("Data", ['$http',
function($http, ) { // This service connects to our REST API
var serviceBase = 'service/';
var obj = {};
obj.get = function(q,p) {
console.log(p);
return $http.get(serviceBase + q + ".php",{params:p}).then(function (results) {
return results.data;
});
};
obj.post = function(q, object) {
return $http.post(serviceBase + q + ".php", object).then(function(results) {
return results.data;
});
};
obj.put = function(q, object) {
return $http.put(serviceBase + q + ".php", object).then(function(results) {
return results.data;
});
};
obj.delete = function(q) {
return $http.delete(serviceBase + q + ".php").then(function(results) {
return results.data;
});
};
return obj;
}
]);
for POST work fine, but for GET doesn't work :(
New Edit
Here you can see how is that I have the code, how use and the response
Edit - Finalized
At the end, I resolved using $httpParamSerializer to serialize the json object and put it directly on call to empresa.php
Thanks to all for the help!!!
Use $httpParamSerializer to build the url query for you.
var params = {id:-1,action:"get"};
var query = $httpParamSerializer(params);
$http.get("empresa.php?" + query);
Try not using the $http.get shortcut method.
$http({
url: "empresa.php",
method: "GET",
params: {id:-1, action:"get"}
});
Or else you can create the url yourself.
$http.get('empresa.php?id=' + -1 + '&action=' + 'get');

Promise Chains in angularjs

I am uploading attachments using rest api in SharePoint 2013,for this I need to call upload attachment method on synchronous.
Because If I call upload attachment method asynchronous I am getting 409 conflict error.
How to chain promise objects in for loop.i.e I want to call second attachment method in first attachment success and so on..
Please help me in best approach of chaining of promises in for loop.
Common method for saving attachments:
var saveFileAngularJS = function (file, url) {
var deferred = $q.defer();
getFileBuffer(file).then(function (fileArrBuffer) {
$http({
method: 'POST',
url: baseUrl + url,
headers: {
'Accept': 'application/json;odata=verbose',
'Content-Type': undefined,
'X-RequestDigest': jQuery("#__REQUESTDIGEST").val()
},
data: new Uint8Array(fileArrBuffer),
transformRequest: []
}).then(function successCallback(data) {
deferred.resolve(data);
alert('Successfully saved.', data);
}, function errorCallback(error) {
deferred.reject(error);
alert('Failed to save!!!.', error);
});
});
return deferred.promise;
};
Method calling :
for (var i = 0; i < $scope.files.length; i++) {
var file = $scope.files[i]._file;
var response = lssDealService.insertAttachment(transactionId, file);
}
var insertAttachment = function (dealId, file) {
var attachmentUrl = listEndPoint + "/GetByTitle('TransactionList')/GetItemById(" + dealId + ")/AttachmentFiles/add(FileName='" + file.name + "')";
return baseService.saveFile(file, attachmentUrl);
};
Insert attachment will call SaveFile method.
I want to run this for loop sequentially, once the loop has been completed I need to process all promises and display success message to user.
Please help me to writing the chaining promises in effective way.
Lets say you have the attachements as an array,
function uploadMyAttachements() {
return myAttachements.reduce(function(promise, attachment) {
return promise.then(function () {
return upload(attachment);
})
.then(function(result) {
console.log('RESULT FOR LAST UPLOAD', result);
});
}, Promise.resolve());
}
function upload(attachment) {
//upload the attachment to sharepoint
//and return a promise here
}
uploadMyAttachements().catch(function(err) {
//if anything in the promise chain fails
//it stops then and there and CATCHED here
});
Now whats happening here, using the Array.reduce, we create a chain of promises like shown below
upload(0).then(handleResult_0).upload(1).then(handleResult_1)....
and it execute one by one as you expected
Throwing my 2 pennies:
$scope.attachments = []; //modified via binding.
function uploadAttachments(){
//Reduce the files array into a promise array with the uploadOne method
//then return the promise when every promise has been resolved or one has rejected.
return $q.all($scope.attachments.reduce(uploadOne, []));
}
function uploadOne(file){
//Upload one, return promise. Use $http or $resource.
}
//Note - a more advanced way of doing this would be to send the files as batch (one
//$http post) as FormData. There are some good wrappers for angular.
$scope.upload = function(){
uploadAttachments().then(function(results){
//Array of results
}).catch(function(e){
//Error handler
});
}

I set the service data,but after $http done, I cannot get the service data

My service define like this:
module.factory('portfolio',function(){
var data;
var selectedPort;
return{
getData: function(){
return data;
},
setData:function(portfolios){
data = portfolios;
},
getSelectedPort:function(){
return selectedPort;
},
setSelectedPort:function(portfolioDetail){
selectedPort = portfolioDetail;
}
}
});
And in my controller the code as follows:
module.controller('portfoliosController', function($scope,$http, alertService,stockService, userDataService, portfolio){
var req = {
method: 'get',
url: 'www.facebook.com',
headers: {
'Authorization': userDataService.getToken()
}
};
$http(req).then(function(reponse){
$scope.portfoliosPriceList = reponse['data'];
portfolio.setData($scope.portfoliosPriceList);
console.log(portfolio.getData())//At here,I can get the portfolio's data
}, function(){
alertService.setMessge("System maintenance , please try again later");
alertService.alert();
});
console.log(portfolio.getData())//At here, I cannot get the portfolio's data
});
the error is
Error: undefined is not an object (evaluating 'message.substr')
Anybody can help me to solve this problem?Actually, I really do not understand, why I cannot get the data outside the $http
The request that you do with the $http service is done asynchronously, so the callback that you pass to the .send is not immediately invoked.
The code that follows (the console.log) is executed just after the $http(req) call is made but before the callback is called when the request is responded.
Maybe you will understand better with an simpler example:
function portfoliosController() {
var data = 'Initial Data. ',
content = document.getElementById('content');
// setTimeout would be your $http.send(req)
// calledLater would be your .then(function() { ... })
setTimeout(function calledLater() {
data = 'Data coming from the server takes some time to arrive...';
content.innerHTML = content.innerHTML + data;
}, 1000);
content.innerHTML = content.innerHTML + data;
}
portfoliosController();
<div id="content">
This is because javascript is asynchronous, so the code:
portfolio.getData()
Is maybe executing before the data is returned from the service.
In this case, you should only use the data of the portfolio just after the request is complete (inside the .then() function of $http) or put a promise.
Here is the documentation for angular promises:
https://docs.angularjs.org/api/ng/service/$q

To call function repeatedly itself until it satisfies the condition using promise-Angularjs

I want to post images on server continuously and i am doing this by putting it in a loop of images length.I want to call the function again on the success of previous image upload using promises.
Below is the code i am using
$scope.questionimageuploadfun = function(surveyid, questionid, type, questions) {
angular.forEach(questions, function(value, key) {
$scope.upload = $upload.upload({
url: 'questions/' + questionid + '/options/' + value.id,
file: value.file,
fileFormDataName: 'myfile',
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
// file is uploaded successfully
if (!data.error && type == "new") {
toaster.pop('success', "Question", "Question added succesfully");
}
})
// });
}
I searched for the way to use promises but no success.I want to do this on success of every call till the condition gets satisfies
To create a controlled infinite loop with promises can be a bit tricky.
I structured a basic function here for you, but you need to modify it to work to your
$scope.questionImageUploadFun = function(surveyid,questionid,type,questions){
var defer = $q.defer(); // the deferred object, a promise of work to be done
$http.get('someUrl', parameters).then(function(response){
// do something with success response
defer.resolve(response);
}, function(reasonForFail){
// do something with failure response
defer.reject(reasonForFail);
});
return defer.promise; // return the promise
};
// define success function
var onSuccess = function(response){
// declare local parameters here
// call function again
$scope.questionImageUploadFun().then(onSuccess); // success function should call itself again on the next success
};
var onFailure = function(reason){
// do something else?
};
var surveyId = 1;
var questionId = 1;
var type = 1;
var question = 1;
// call the function, since it returns a promise, you can tag a then() on the end of it, and run the success function.
$scope.questionImageUploadFun(surveyid,questionid,type,questions).then(onSuccess);

Chaining Angular Promises

I am having some trouble chaining promises in Angular. What I want to do is fetch my project object from the API, then check if the project owner has any containers, if they do, trigger the another GET to retrieve the container. In the end the container assigned to scope should either be null or the object retrieved from the API.
Right now, this example below resolves immediately to the second then function, and I get the error, TypeError: Cannot read property 'owner' of undefined. What am I doing wrong?
$http.get('/api/projects/' + id).then(function (data) {
$scope.project = data.project;
return data.project;
}).then(function (project) {
var containers = project.owner.containers;
if (containers.length) {
return $http.get('/api/containers/' + containers[0]);
} else {
return null
}
}).then(function (container) {
$scope.container = container;
});
Ah, turns out the data from passed into then is inside a field, so I needed to do
$scope.project = data.data.project;
return data.data.project;
Your example code works, but what if the $http call fails because of a 404? Or you want to later want to add some extra business logic?
In general you want to handle 'negative' cases using a rejecting promise, to have more control over the chaining flow.
$http.get('/api/projects/' + id).then(function (data) {
$scope.project = data.data.project;
return data.data.project;
}).then(function (project) {
var containers = project.owner.containers;
if (containers.length) {
return $q.reject('containers empty');
}
return $http.get('/api/containers/' + containers[0]);
}).then(function (container) {
$scope.container = container;
}).except(function (response) {
console.log(response); // 'containers empty' or $http response object
$scope.container = null;
});

Resources