Zyx Sun
Zyx Sun

Reputation: 439

Convert angularjs $http response to string/JSON

Please be patient with me since I'm a beginner.

So I have this factory $http request to the server

$http request

factory.checkPollCodeIfAvail = function(x){
    code = x;
    return $http({
        method: 'POST',
        data: {
            'action' : 'checkPollCode',
            'pollCode' : code
        },
        url: 'http://localhost/poll/api.php',
        transformRequest:function(obj) {
            //transform header query into 'myVar1=var1Value&myVar2=var2Value'
            var str=[];
            for(var p in obj){
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]))
            }
            console.log(str.join("&"));
            return str.join("&"); 
        },
        headers:{'Content-Type':'application/x-www-form-urlencoded'}
    }).then(function(response){
        var i = response.data.message.toString();
        console.log(i);
        return i;
    });
};

which would supposedly return i to my controller:

Controller:

pollCodeStatus = pollFactory.checkPollCodeIfAvail('qwe123');
console.log(pollCodeStatus.toString());

when I try to console.log the i in the $http request i will get a value string but when I tried console.log in the controller what I will get is an object [object Object].

So can I convert an $http object to a string or even json data? if yes, how?

Thank you very much.

Upvotes: 1

Views: 2824

Answers (3)

Prateek Gupta
Prateek Gupta

Reputation: 1169

$http is for making an asynchronous calls and $http returns a promise object which needs to be resolved before accessing it. But in your code you have used it in a synchronous way .

You need to create a deferred object in the factory and return this deferred object. So, here is the updated code :

Inject $q into the factory first.

 factory.checkPollCodeIfAvail = function(x){
    code = x;
    var defered = $q.defer();
    return $http({
        method: 'POST',
        data: {
            'action' : 'checkPollCode',
            'pollCode' : code
        },
        url: 'http://localhost/poll/api.php',
        transformRequest:function(obj) {
            //transform header query into 'myVar1=var1Value&myVar2=var2Value'
            var str=[];
            for(var p in obj){
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]))
            }
            console.log(str.join("&"));
            return str.join("&"); 
        },
        headers:{'Content-Type':'application/x-www-form-urlencoded'}
    }).then(function(response){
        defered.resolve(response.data.message.toString());
        var i = response.data.message.toString();
        console.log(i);
        return i;
    });
  return defered.promise;
};

And in your controller you will resolve like this:

pollFactory.checkPollCodeIfAvail('qwe123').then(function(resp){
console.log(resp);
});

This is the correct way of handling async calls from factory or service. Hope this solves your problem. :)

Upvotes: 0

Junbang Huang
Junbang Huang

Reputation: 1967

Your problem is $http return a promise object, that means your pollCodeStatus is a promise object.

The function you provide to then will be called if the promise object is resolved. This line return i is the return of the function you provide to then.

If you want to get i, you can use a global variable. Like the following:

var i 
factory.checkPollCodeIfAvail = function(x){
...
.then(function(response){
    i = response.data.message.toString();
});
};
console.log(i);

Upvotes: 1

Maria Ines Parnisari
Maria Ines Parnisari

Reputation: 17496

factory.checkPollCodeIfAvail = function(x){
    code = x;
    return $http({

Your checkPollCodeIfAvail function is not returning i, it's returning a Promise that will eventually resolve to i. What does this mean? The HTTP call is asynchronous, so you need to wait until it finishes.

So in order to capture i in the controller, you need to do this:

pollFactory.checkPollCodeIfAvail('qwe123')
.then(function (pollCodeStatus) {
    console.log(pollCodeStatus)
})

Right now, as you've written it...

pollCodeStatus = pollFactory.checkPollCodeIfAvail('qwe123');
console.log(pollCodeStatus.toString());

...you are kind of expecting checkPollCodeIfAvail to run synchronously, which is not the case.

Upvotes: 2

Related Questions