[英]$q and resolving promises in Angular
我不知道該怎么回事。 我試圖在嵌套方法中返回結果,但更願意在后面顯示的兩種不同方法中返回結果:
$scope.relatedContacts = function (accountId) {
if (!lodash.isNil(accountId)) {
try {
return restangular.one('user')
.one('contactimages')
.get({ 'mappedRelatedContactsPath': $scope.mappedRelatedContactsPath, "account": accountId })
.then(function (response) {
return response.data;});
}
}
寧願修復下面的例子:
$scope.relatedContacts = function (accountId) {
if (!lodash.isNil(accountId)) {
try {
var deferred = $q.defer();
return restangular.one('user')
.one('contactimages')
.get({ 'mappedRelatedContactsPath': $scope.mappedRelatedContactsPath, "account": accountId })
return deferred.promise;
}
catch (err) {
$scope.contactsPopulated = false;
}
}
}
$scope.relatedContacts().then(function (response) {
//Some logic here
}
目前我得到:“TypeError:無法讀取屬性'然后'未定義”
謝謝大家
首先,請記住一致性。 isNil
如果在某些情況下使你的函數沒有返回任何東西(當沒有提供accountId
時,你將得到TypeError: Cannot read property 'then' of undefined "
錯誤。
您有兩種方法可以解決您的問題。
第一種方式:
$scope.relatedContacts = function (accountId) {
return $q(function(resolve, reject) {
if (!lodash.isNil(accountId)) {
try {
return restangular.one('user')
.one('contactimages')
.get({ 'mappedRelatedContactsPath': $scope.mappedRelatedContactsPath, "account": accountId })
.then(function(response) {
resolve(response.data)
}, reject);
}
catch (err) {
$scope.contactsPopulated = false;
reject(err);
}
}
});
};
第二種方式(使用延遲)。
$scope.relatedContacts = function (accountId) {
var def = $q.defer();
if (!lodash.isNil(accountId)) {
try {
restangular.one('user')
.one('contactimages')
.get({ 'mappedRelatedContactsPath': $scope.mappedRelatedContactsPath, "account": accountId })
.then(function(response) {
def.resolve(response.data)
}, def.reject);
}
catch (err) {
$scope.contactsPopulated = false;
def.reject(err);
}
}
return def;
};
您應查看有關$q
服務的官方參考: https : //docs.angularjs.org/api/ng/service/$q
有許多典型的承諾用法的例子。
這是我用來返回值並添加其他方法來處理響應。
$scope.relatedContacts = function (accountId) {
var deferred = $q.defer();
if (!lodash.isNil(accountId)) {
try {
deferred.resolve(restangular.one('user')
.one('contactimages')
.get({ 'mappedRelatedContactsPath': $scope.mappedRelatedContactsPath, "account": accountId }));
}
catch (err) {
$scope.contactsPopulated = false;
deferred.reject(err);
}
}
deferred.promise.then(function (response) {
var tests = response;
return $q.when();
},
function () {
console.log("1st reject");
return $q.reject();
});
return deferred.promise;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.