简体   繁体   中英

angular $http vs factory to call http request

Can someone point out whythese two codes doesn't work the same way? $http.post request works fine and gives me the response back on the other hand using a factory to do the post request it gives me [object object] response but network payload shows the username and password .

html:

<input type="text" class="form-control" id="username" placeholder="Username" ng-model="vm.userlogin.username">

<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" ng-model="vm.userlogin.password">

straight from controller:

$http.post('/api/login/', vm.userlogin).success(function(response){
            localStorage.setItem('key', response);
            $rootScope.isLoggedIn = true;
            $location.path('/dashboard');
        }).error(function(error){
            console.log('err');
        });

using factory:

signupService.login(vm.userlogin.username, vm.userlogin.password)
            .then(function(response){
                console.log(response);
                localStorage.setItem('key', response);
                $rootScope.isLoggedIn = true;
                $location.path('/dashboard');
        });

login factory:

function _login(username, password){
        var data = {
            username: username,
            password: password
        };
        return $http({
            method: 'POST',
            url: '/api/login/',
            data: data
        });
    };

response object in first then() of $http promise is not the same as in success() . Your data is in the data property of it

Try using response.data

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