如何管理AngularJS http请求调用

时间:2017-02-23 18:14:18

标签: javascript jquery angularjs reactjs https

Please find attached what I want to achieved

我有一段发送双重HTTP请求的代码。我想首先发出身份验证请求,如果是,则执行下一条语句(只返回$ http承诺)。如何在 angularJS 中执行此操作。截至目前,它正在返回undefined。

dmdb._login_request = function(credentials, conf) {
    var p = {
        '_method': 'POST',
        'data[User][username]': credentials.login,
        'data[User][password]': credentials.password
    };
    conf.headers = {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    };
    var userData = {
        'username': 'mbah',
        'password': 'abc@123',
        'applicationid': '1'
    };
    $http.post('myapp.com/authenticate/', userData, con).success(function(data) {
        if (data.success) {
            return $http.post(this.url + 'users/login', $.param(p), conf);
        }
        return $q.when('failed');
    })
};

2 个答案:

答案 0 :(得分:3)

使用promise chain来一个接一个地调用请求。

function firstReq(userData, conf) {
    return $http({
        method: 'POST',
        url: 'myapp.com/authenticate/',
        headers: conf.headers,
        data: userData
    })
}

function secondReq(p, conf) {
    return $http({
        method: 'POST',
        url: this.url + 'users/login',
        headers: conf.headers,
        data: $.param(p)
    })
}
$scope.processform = function() {
    var userData = {
        'username': 'mbah',
        'password': 'abc@123',
        'applicationid': '1'
    };
    var p = {
        '_method': 'POST',
        'data[User][username]': credentials.login,
        'data[User][password]': credentials.password
    };
    conf.headers = {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    };
    firstReq(userData, conf)
        .then(function(response) {
            console.log(response.data);
            return secondReq(p, conf);
        })
        .then(function(response) {
            console.log(response.data);
        })
}

答案 1 :(得分:1)

my_obj._login_request = function (credentials,conf) {


  var url_=this.url;

        var p = {
        '_method': 'POST',
        'data[User][username]': credentials.login,
        'data[User][password]': credentials.password
    };
    conf.headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'};


    var userData={
    'username':'mbah',
    'password':'abc@123',
    'applicationid':'1'
};

var deferred = $q.defer();

$http.post('auth/path/UserLogin/Login',userData).success(function(data){
       console.log(data);
        if(!angular.isDefined(data.status)){

                    deferred.resolve($http.post(url_+'/users/login',$.param(p),conf));
        }
        else{
             deferred.reject();
        }
})

 return deferred.promise;

};

这是我的最终代码及其按预期工作。谢谢帮助人员