我是 Angular JS 的新手。我试图在 $http 的响应中实现 $http。
我的问题是,当我调用 $http 来响应另一个 $http 时。它不显示 View 中的数据。该 View 在第二次 $http 调用之前呈现。我用过 promise ,但没有运气。这是我通过稍微更改使用的其他答案的代码。
angular.module('App', [])
.controller('Ctrl', function($scope, resultsFactory) {
resultsFactory.all().then(
function(res){
$scope.results = res;
},
function(err){
console.error(err);
}
);
})
.factory('resultsFactory', function($http, $timeout, $q) {
var results = {};
function _all(){
var d = $q.defer();
$http({
url: url,
method: 'POST'
}).then(function (response) {
var f = {};
f.id = response.data.id;
f.name = response.data.name;
$http({
url: url,
data: "id="+response.data.parent_id,
method: 'POST'
}).then(function (response1) {
f.parentname = response1.name;
d.resolve(f);
});
});
return d.promise;
}
results.all = _all;
return results;
});
ID 和名称在 View 中正确显示,但没有显示父名称。我已经调试过了渲染 View 时未定义。渲染后,将它们的值设置为parentname。任何人都可以帮我解决这个问题吗?
最佳答案
您不需要为此推迟:只需链接 promise 即可:
return $http({
url: url,
method: 'POST'
}).then(function (response) {
var data = {};
data.id = response.data.id;
data.name = response.data.name;
return $http({
url: url,
data: "id="+response.data.parent_id,
method: 'POST'
}).then(function (response1) {
data.parentname = response1.name;
return data;
});
});
关于javascript - 调用 $http 来响应另一个 http - Angular js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35922997/