Angularjs 用另一个值创建角度承诺
我有一个返回一些数据的web服务。为了防止代码重复,我想将http请求调用移动到angular service:Angularjs 用另一个值创建角度承诺,angularjs,promise,angular-promise,Angularjs,Promise,Angular Promise,我有一个返回一些数据的web服务。为了防止代码重复,我想将http请求调用移动到angular service: angular.module('abc', []) .factory('def', function () { return { getData: function () { return $http.post('/path/', {}); } }; });
angular.module('abc', [])
.factory('def', function () {
return {
getData: function () {
return $http.post('/path/', {});
}
};
});
一切都很好,但必要的数据在复杂的对象中,我每次都要写:
def.getData().then(function (response) {
scope.obj = response.data.qwe.rty.xyz;
});
返回承诺的最简单方法是什么,它将把response.data.qwe.rty.xyz的值直接发送到successCallback
?我可以这样写:
def.getData().then(function (obj) {
scope.obj = obj;
});
angular.module('abc', [])
.factory('def', function () {
return {
getData: function () {
return $http.post('/path/', {})
.then(function(response) {
return response.data.qwe.rty.xyz;
});
}
};
});
调用$http.post('/path/',{})
返回一个承诺,然后调用then()
。请注意,then()
还返回一个承诺,因此您可以链接调用。因此,您的代码可能如下所示:
def.getData().then(function (obj) {
scope.obj = obj;
});
angular.module('abc', [])
.factory('def', function () {
return {
getData: function () {
return $http.post('/path/', {})
.then(function(response) {
return response.data.qwe.rty.xyz;
});
}
};
});
调用$http.post('/path/',{})
返回一个承诺,然后调用then()
。请注意,then()
还返回一个承诺,因此您可以链接调用。因此,您的代码可能如下所示:
def.getData().then(function (obj) {
scope.obj = obj;
});
angular.module('abc', [])
.factory('def', function () {
return {
getData: function () {
return $http.post('/path/', {})
.then(function(response) {
return response.data.qwe.rty.xyz;
});
}
};
});
您可以使用在$q
提供程序中实现的延迟行为
像这样:
angular.module('abc', [])
.factory('def', function ($q) {
return {
getData: function () {
var def = $q.defer
$http.post('/path/', {}).then(function(response){
def.resolve(response.data.qwe.rty.xyz)
});
return def.promise;
}
};
});
并在控制器中使用它,如:
def.getData().then(function (response) {
scope.obj = response;
});
您可以使用在$q
提供程序中实现的延迟行为
像这样:
angular.module('abc', [])
.factory('def', function ($q) {
return {
getData: function () {
var def = $q.defer
$http.post('/path/', {}).then(function(response){
def.resolve(response.data.qwe.rty.xyz)
});
return def.promise;
}
};
});
并在控制器中使用它,如:
def.getData().then(function (response) {
scope.obj = response;
});