我有以下项目结构:
- 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
。
所以,鉴于我的情况,如果我没有userData,我想取消请求,我该如何做到这一点?
答案 0 :(得分:1)
你的电话应该返回一个承诺。如果有用户,则从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;
}