[英]How to break/return an Angular asynchronous call in AngularJS
我有以下項目結構:
PageController.js
BusinessService.js
NetworkManager.js
在我的PageController中,我有以下調用:
var getSomething = this._businessService.getMeSomething().then(function(response) {
alert("my response: " + response);
});
在我的BusinessService中:
getMeSometing: function() {
var user = this.getUserData();
if(user) {
var sendPromise = this._networkManager.getAnotherThing(user.id).then(function(response) {
alert("And another response: " + response);
});
} else {
$q.reject({ message: 'Rejecting this promise' });
}
},
在NetworkManager
類中進行http調用。 所以這里的問題是,當我沒有用戶數據時,我想中斷呼叫,因此我使用了reject
。
這將返回錯誤: Cannot read property 'then' of undefined
有關PageController
的調用Cannot read property 'then' of undefined
。
因此,根據我的情況,如果沒有userData,我想在哪里取消請求,該如何完成呢?
您的電話應該返回一個承諾。 如果有用戶,則從getAnotherThing
返回承諾,否則,從$q.reject
返回承諾...
getMeSomething: function() {
var user = this.getUserData();
var sendPromise;
if(user) {
sendPromise = this._networkManager.getAnotherThing(user.id).then(function(response) {
alert("And another response: " + response);
// you probably want to return the data if successful (either response or response.data, depending on what response is)
return response.data;
});
} else {
sendPromise = $q.reject({ message: 'Rejecting this promise' });
}
return sendPromise;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.