Bhushan Goel
Bhushan Goel

Reputation: 2144

using factory service for http calls and using them through controller

I am developing an app on MEAN stack. I made factory to handle my http requests and then using that service in my controller.

service

.factory('dataSvc', function($q, $http, $timeout, $rootScope, $resource) {

var dataSvc = {};

dataSvc.list = function(options) {
    var defer = $q.defer();
    return $http.get(options.url).success(function(data) {
        console.log('========data========', data)
        defer.resolve(data);
    }).error(function(err){
        console.log('======err=======', err)
        defer.reject(err);
    });

    return defer.promise;
}

return dataSvc;
});

I have two questions regarding this:

  1. even if I get 401 status from backend I always end up in success function, So what I am doing wrong here.

  2. also If I remove return from $http.get then the functionality breaks. So What is the need for this return keyword in front of $http.get

controller

dataSvc.list({url: '/api/users'}).then(function(result) {
    console.log('result here===========', result);
    if(result.status == 401) {

    }
    else {

    }

});

and also what is the difference between then method and success and error methods provided by angular ?

Upvotes: 2

Views: 54

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

You could return $http.get object rather than creating your own promise, because $http.get does return a promise object itself. After that you need to use .then function over that $http.get which will have 1st function which will get call when promise gets resolved & other function will get called when promise gets rejected.

Then response object your received in .then function has various data present in it.

data – {string|Object} – The response body transformed with the transform functions. status – {number} – HTTP status code of the response.

headers – {function([headerName])} – Header getter function.

config – {Object} – The configuration object that was used to generate the request.

statusText – {string} – HTTP status text of the response.

Code

dataSvc.list = function(options) {
    var defer = $q.defer();
    return $http.get(options.url).then(function(response) {
        console.log('========response========', response)
        return response;
    }).error(function(err){
        console.log('======err=======', err)
        return err;
    });
}

Controller

dataSvc.list({url: '/api/users'}).then(function(result) {
    console.log('result here===========', result);
    if(result.status == 401) {

    }
    else {

    }

});

Upvotes: 1

Related Questions