简体   繁体   中英

$http and factory - how does this pattern work?

Below is the recommended way to get data into a controller from a factory using $http -- according to https://github.com/johnpapa/angularjs-styleguide

What i don't get is how the two success callbacks on $http work (i commented what i think the two callbacks are). 1) What is the point of the first callback? 2) Where does vm.avengers point to? Is it a reference to another object? 3) is 'data' in the second callback = 'response.data.results' from the first? 4) I'm counting 3 total callbacks chained, is that correct?

PS i already know about promises, but want to learn this pattern specifically

The factory

 /* recommended */

// dataservice factory
angular
.module('app.core')
.factory('dataservice', dataservice);

 dataservice.$inject = ['$http', 'logger'];

function dataservice($http, logger) {
return {
    getAvengers: getAvengers
};

function getAvengers() {
    return $http.get('/api/maa')
        .then(getAvengersComplete)
        .catch(getAvengersFailed);

    //Callback One
    function getAvengersComplete(response) {
        return response.data.results;
    }

    function getAvengersFailed(error) {
        logger.error('XHR Failed for getAvengers.' + error.data);
    }
}

}

The Controller

  function Avengers(dataservice, logger) {
  var vm = this;
  vm.avengers = [];

  activate();

  function activate() {
    return getAvengers().then(function() { //Callback 3
        logger.info('Activated Avengers View');
    });
}

function getAvengers() {
    return dataservice.getAvengers()
        .then(function(data) { //Callback 2
            vm.avengers = data;
            return vm.avengers;
        });
}}   
  1. The point of this first callback is to do any manipulation with the data prior to it entering into the app and to actually pull the useful data out of the http response object.
  2. vm.avengers is declared at the top of your controller. It's using the "controller as" syntax and is being put on a reference to the "this" object of the controller. You're ultimately using vm.avengers to access the data in the view.
  3. Correct.
  4. HTTP Call -> getAvengersComplete -> getAvengers, so correct 3 callbacks.

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