简体   繁体   中英

How to do HTTP chaining in AngularJS

I am trying to do HTTP chaining. If a HTTP status is non 200 then i want to break out of promise chain. But with my current solution it is being executed till end even in case of error or non 200 status.

factory.login=function(username,password){
        var url=String(myconfig.url)+"authentication/token/new";
        var requestToken="";
        var sessionID="";
        var defer=$q.defer();

        $http({
            url:url,
            params:{
                api_key:"my API Key",

            }
        }).then(validateWithLogin,HTTPErrorHandler)
            .then(getSessionID,HTTPErrorHandler)
            .then(function(data){
                if (data.status!=200){
                    defer.reject(data);
                }
            sessionID=data.data.session_id;
            $cookies.put("sessionid",sessionID);
        },HTTPErrorHandler);
        function HTTPErrorHandler(data){
            console.log("HTTP Error happened");
            console.log(data);
            defer.reject("http error");  
        }
        function validateWithLogin(data){
            if (data.status!=200){
                defer.reject(data);
            }
            requestToken=data.data.request_token;
            console.log("validate with login"+data);
            return $http({
       url:String(myconfig.url)+"authentication/token/validate_with_login",
                params:{
                    api_key:"my API Key",
                    username:username,
                    password:password,
                    request_token:requestToken
                }
            })
        }
        function getSessionID(data){
            if (data.status!=200){
                defer.reject(data);
            }
            return $http({
                url:String(myconfig.url)+"authentication/session/new",
                params:{
                    api_key:"my API Key",
                    request_token:requestToken
                }
            })
        }

    };

Because It's not enough to just reject your promise but you have to return with your deferred object.

I'd suggest to use the sorthand version of it: return $q.reject();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM