如何在AngularJS中中断/返回Angular异步调用

时间:2014-07-25 14:56:28

标签: javascript angularjs asynchronous angular-promise

我有以下项目结构:
- 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,我想取消请求,我该如何做到这一点?

1 个答案:

答案 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;
}