0

我有以下项目结构:
- PageController.js
- BusinessService.js
-NetworkManager.js

在我的 PageController 我有以下调用:

var getSomething = this._businessService.getMeSomething().then(function(response) {
    alert("my response: " + response);
});

在我的业务服务中:

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' });
    }
},

http 调用正在NetworkManager课堂上进行。所以这里的问题是,当我没有用户数据时,我想中断通话,所以我使用reject.
这将返回一个错误:Cannot read property 'then' of undefined关于PageController.

那么,考虑到我的情况,如果我没有 userData,我想取消请求,我该如何完成呢?

4

1 回答 1

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;
}
于 2014-07-25T15:10:36.393 回答