weird javascript behavior - logging in chrome - javascript

I have something really weird going on in my code. An object is sent by the server in a correct way, and it even arrives in my angular factory and i log the object the following shows:
notice how course_id is an integer and 20 when the object is not expanded, when i expand it becomes a string and 19. I am going insane. Has anyone ever had this before? I'm sure there's a reason to this madness!
my angular service:
/*********************************
* get one batch
*********************************/
get: function(batch_id) {
var deferred = $q.defer();
var request = $http({
method: 'GET',
url: ENV.api + 'batch/get/' + batch_id,
headers: {
'Content-Type': 'application/json'
}
});
request
.success(function(result) {
console.log(result);
deferred.resolve(result);
})
.error(function(error) {
console.error(error);
deferred.reject(error);
});
return deferred.promise;
},

i have figured out a way around it, and a possible answer:
https://docs.angularjs.org/api/ng/function/angular.copy
and
Why do I need to use angular.copy in my factory?
/*********************************
* get one batch
*********************************/
get: function(batch_id) {
var deferred = $q.defer();
var request = $http({
method: 'GET',
url: ENV.api + 'batch/get/' + batch_id,
headers: {
'Content-Type': 'application/json'
}
});
request
.success(function(result) {
console.log(angular.copy(result));
deferred.resolve(angular.copy(result));
})
.error(function(error) {
console.error(error);
deferred.reject(error);
});
return deferred.promise;
},

Related

In Angular JS $scope variable value assign from $http

I'm new to angular js. Here i have the code: I receive the response data like number. In this code how i assign the response data as $scope.vote_counting. In this code does not return anything.
$scope.votes = function(){
var votes = $http({
method: "post",
url: "/getVotes",
data: { id: $scope.Id}
}).success(function(response){
});
return votes;
}
Please anyone help to this.
Simply call the $http. It does not have to be in a function
$http({
method: "post",
url: "/getVotes",
data: { id: $scope.Id }
}).then(function(response) {
//handle success
$scope.votes_counting = response.data;
}, function(error){
//handle error
});
The sort version is
$http.post("/getVotes", { id: $scope.Id }).then(function(response) {
//handle success
$scope.votes_counting = response.data;
}, function(error) {
//handle error
})
Note : You are using a POST method but a GET method seems more appropriate in your case (getVotes)
I've added a snippet, which shows the basic handling of promises. Here, I've used a service to mock a http call. The response is attached to a scope variable, which is presented in the view.
angular.module('TestApp', [])
.factory('MockHttp', function($q) {
return {
getMockData: function() {
return $q.when(['A', 'B', 'C']);
}
};
})
.controller('TestController', function($scope, MockHttp) {
$scope.res = null;
MockHttp.getMockData()
.then(function(res)  {
$scope.res = res;
})
.catch(function(err) {
console.log(err);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="TestApp">
<div ng-controller="TestController">
{{res}}
</div>
</div>
The $http function does not return the response of the server. But as you have already figured out you can use the success function to get the servers response. Simply set $scope.votes value in the success function like this:
$http({
method: "post",
url: "/getVotes",
data: { id: $scope.Id}
}).success(function(response){
$scope.votes = response
});
The easiest is probably using $http.post. Note that success is deprecated in favour of then:
$scope.retrieveVotes = function(){
$http.post('/getVotes', {id : $scope.id}).then(function(response){
$scope.votes = response.data;
});
}
Also note that $http calls are asynchronous so calling retrieveVotes is also asynchronous.

Return Object in $rootScope Function (AngularJS)

I am trying to return an object from a $rootScope function called retrieveUser() in AngularJS. The object is returned. I have run console.log() on the response of the function ran when $http is successful. Here is my $rootScope function:
$rootScope.retrieveUser = function() {
var apiUrl = "http://104.251.218.29:8080";
if($cookies.get('tundraSessionString')) {
var cookie = $cookies.get('tundraSessionString');
$http({
method: "POST",
url: apiUrl + "/api/master/v1/auth/checkauth",
data: "sessionString=" + cookie,
headers: {
'Content-Type' : 'application/x-www-form-urlencoded;',
'Cache-Control': 'no-cache'
}
}).then(function mySuccess(response) {
if(response.data.event == "error") {
window.location = "/auth/logout";
} else {
return response.data;
}
})
} else {
window.location = "/auth/login";
}
};
With this method, I access it in my controller such as this (and console.log() just to test my work):
vm.user = $rootScope.retrieveUser();
console.log($rootScope.retrieveUser());
But, I have yet to get this to work. I have tried specifying specific objects in an array in my $rootScope function. I know it runs, because I have the $rootScope consoling something when it is run, and it shows a console.log() of the response of the $http request. It looks like this:
Object {event: "success", table: Object}
event:"success"
table:Object
__proto__:Object
Yet, when I console.log() the vm.user with the function $rootScope.retrieveUser(), even though the function is supposed to be returning the object, I simply receive "undefined".
I have been banging my head on this for days, read some articles on functions/objects and I still cannot figure this out. We're two days in.
try this:
if($cookies.get('tundraSessionString')) {
var cookie = $cookies.get('tundraSessionString');
//return a promise
return $http({
method: "POST",
url: apiUrl + "/api/master/v1/auth/checkauth",
data: "sessionString=" + cookie,
headers: {
'Content-Type' : 'application/x-www-form-urlencoded;',
'Cache-Control': 'no-cache'
}
}).then(function mySuccess(response) {
if(response.data.event == "error") {
window.location = "/auth/logout";
}
else {
return response.data;
}
})
}
else {
window.location = "/auth/login";
}
and
$rootScope.retrieveUser().then(function(user){vm.user = user;})
What you are returning from retrieveUser when your cookie is set is what $http returns, which is a promise. Try this:
$rootScope.retrieveUser().then(function(user){vm.user = user;})
retrieveUser fn doesn't return your data :)
$http is asynchronous function and you should read about promises
function handleUser(user){
//do something
}
function retrieveUser(callback){
$http({...}).then(function(response){
callback(response.data.user);
});
}
//how to use it:
retrieveUser(handleUser);
but first of all you may need a service for getting some data instead of using $rootScope
and secondly you can pass a user in your template in script tag
then you don't need another http request and user will be globaly available
<script>var user=<?php echo json_encode($user);?></script>

Angular - How can i pass a parameter into a deferred promise?

Working on my first Angular app here so excuse me if question not clear.
I have a service which gets from my api using a group variable in the header.
var theReq = {
method: 'GET',
url: API + '/homeq',
headers: {
'group': 'mobile'
}
};
$http(theReq)
.then(function(data){
deferred.resolve(data);
})
self.getResults = function() {
return deferred.promise;
}
The issue I'm facing is with using the group variable that i specify rather than that preset one.
I can surely pass it into that function (i.e. self.getResults = function(groupToGet)) but how would it get from there to theReq that I process?
Any help appreciated.
Thanks.
You need to modify your function in following manner. $q is the service to create deferred objects. You need to inject it.
self.getResults = function(groupToSet) {
var deferred = $q.defer();
var theReq = {
method: 'GET',
url: API + '/homeq',
headers: {
'group': groupToSet
}
};
$http(theReq)
.then(function(data){
deferred.resolve(data);
})
return deferred.promise;
}
and you can use promise as
self.getResults("mobile").then(function(data) {
//success function here.
}).catch(function(error) {
//error function here
});

Angular Promise Response Checking

I am doing some http calls in Angular and trying to call a different service function if an error occurs. However, regardless of my original service call function return, the promise it returns is always "undefined". Here is some code to give context:
srvc.sendApplicantsToSR = function (applicant) {
var applicantURL = {snip};
var promise = $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
url: applicantURL,
data: applicant
})
.success(function (data) {
return data;
})
.error(function (error) {
return [];
});
return promise;
};
Then, in the controller:
for (var applicant in $scope.applicants) {
$scope.sendATSError($scope.sendApplicantsToSR($scope.applicants[applicant]), applicant);
}
$scope.sendATSError = function (errorCheck, applicantNumber) {
if (angular.isUndefined(errorCheck)) {
console.log(errorCheck);
AtsintegrationsService.applicantErrorHandling($scope.applicants[applicantNumber].dataset.atsApplicantID);
}
};
However, it is always sending errors because every response is undefined. How can I differentiate between the two returns properly? Thank you!
Looking at angular documentation, the sample code is
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
based on that - your first code snippet should be
srvc.sendApplicantsToSR = function(applicant) {
var applicantURL = {
snip
};
return $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
url: applicantURL,
data: applicant
});
};
As others have said, $http's .success() and .error() are deprecated in favour of .then().
But you don't actually need to chain .then() in .sendApplicantsToSR() as you don't need (ever) to process the successfully delivered data or to handle (at that point) the unsuccessful error.
$scope.sendApplicantsToSR = function (applicant) {
var applicantURL = {snip};
return $http({
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST',
url: applicantURL,
data: applicant
});
};
Now, in the caller (your line of code in the for loop), a promise is returned (not data) and that promise will, on settling, go down its success path or its error path. Exactly what happens on these paths is determined entirely by the callback functions you write in one or more chained .thens .
So what you need to write is a kind of inside-out version of what's in the question - with $scope.sendApplicantsToSR() on the outside and $scope.sendATSError() on the inside - and linked together with a .then().
for (var prop in $scope.applicants) {
var applicant = $scope.applicants[prop];
$scope.sendApplicantsToSR(applicant).then(null, $scope.sendATSError.bind(null, applicant));
}
// Above, `null` means do nothing on success, and
// `function(e) {...}` causes the error to be handled appropriately.
// This is the branching you seek!!
And by passing applicant, the error handler, $scope.sendATSError() will simplify to :
$scope.sendATSError = function (applicant) {
return AtsintegrationsService.applicantErrorHandling(applicant.dataset.atsApplicantID); // `return` is potentially important.
};
The only other thing you might want to know is when all the promises have settled but that's best addressed in another question.
You should return your promisse to be handled by the controller itself.
Simplifying:
.factory('myFactory', function() {
return $http.post(...);
})
.controller('ctrl', function(){
myFactory()
.success(function(data){
// this is your data
})
})
Working example:
angular.module('myApp',[])
.factory('myName', function($q, $timeout) {
return function() {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve('Foo');
}, 2000);
return deferred.promise;
}
})
.controller('ctrl', function($scope, myName) {
$scope.greeting = 'Waiting info.';
myName().then(function(data) {
$scope.greeting = 'Hello '+data+'!';
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
{{greeting}}!
</div>

Angular promise after calling a service with $http

I m actually developping an application with angularjs, and I m facing a problem with $http, and the result of an asynchronous service request to my webservice.
Actually, I m using this code :
var promise = undefined;
UserService.getAll = function (callback) {
promise = $http({
url: __ADRS_SRV__ + "users",
method: "GET",
isArray: true
}).success(function(data){
return data;
}).error(function(data){
return $q.reject(data);
});
return promise;
}
This doesnt work, and give me some stuff like, I dont know why :
To know : in my controller, I want to use a really simple syntax like
var data = UserService.getAll();
Do you have any idea how should I process to access my data correctly ?
Thanks for advance
you get the promise in return. There are multiple ways to use this promise.
Example 1 (Use promise in service and return reference of an object):
UserService.getAll = function () {
var dataWrapper = {
myData: {},
error: null
};
$http({
url: __ADRS_SRV__ + "users",
method: "GET",
isArray: true
}).success(function(data){
dataWrapper.myData = data;
}).error(function(data){
dataWrapper.error = true;
return $q.reject(data);
});
return dataWrapper;
}
Example 2 (Return promise and use it directly in the controller):
// service
UserService.getAll = function () {
return $http({
url: __ADRS_SRV__ + "users",
method: "GET",
isArray: true
});
}
// controller
var promise = UserService.getAll();
promise.success(function(data) {
$scope.data = data;
});
Example 3 (Use regular callback):
// service
UserService.getAll = function (cb) {
$http({
url: __ADRS_SRV__ + "users",
method: "GET",
isArray: true
}).success(cb);
}
// controller
UserService.getAll(function(data) {
$scope.data = data;
});
The "stuff" you mention is the very promise you create and return.

Categories

Resources