javascript - 将 angularjs $http 响应转换为 string/JSON

标签 javascript angularjs

请耐心等待我,因为我是初学者。

所以我有这个工厂 $http 请求到服务器

$http 请求

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;
    });
};

这应该将i返回到我的 Controller :

Controller :

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

当我尝试在$http请求中console.log i时,我会得到一个值字符串,但是当我在 Controller 中尝试console.log时 我将得到一个对象[object Object]

那么我可以将 $http 对象转换为字符串甚至 json 数据吗?如果是,怎么办?

非常感谢。

最佳答案

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

您的 checkPollCodeIfAvail 函数没有返回 i,它返回一个 Promise,最终将解析为 i。这是什么意思? HTTP 调用是异步,因此您需要等待直到它完成。

因此,为了在 Controller 中捕获 i,您需要执行以下操作:

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

现在,正如你所写的......

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

...您希望 checkPollCodeIfAvail 同步运行,但事实并非如此。

关于javascript - 将 angularjs $http 响应转换为 string/JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43826963/

相关文章:

javascript - 在 AngularJS ng-repeat 中处理 json 数据

javascript - Angular 位置搜索不适用于 &

javascript - 将值添加到数组的最有效方法

javascript - 无法从列表项内提交的表单中获取表单值

javascript - 模块化 Angular

angularjs - 来自 Controller 的引用 Angular ng-form

javascript - flot x 轴刻度标签未与更改数据上的堆栈条形图对齐

javascript - 如何使用js将包含字母和数字的字符串拆分为不同的变量?

javascript - 通过动态输入计算时间

JavaScript 时差