请耐心等待我,因为我是初学者。
所以我有这个工厂 $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/