AngularJS Best Practice - Factory with multiple methods

早过忘川 提交于 2019-12-06 01:29:24
angular.module('myApp')
    .factory('getFactory', function ($http, $q) {

    //Using revealing Module pattern
    var exposedAPI = {
        methodOne: methodOne,
        methodTwo: methodTwo,
        methodThree: methodThree
    };

    return exposedAPI;

    //Private function, not required to be exposed
    function get(url){
        //$http itself returns a promise, so no need to explicitly create another deferred object
        return $http.get(url)
                .then(function (data) {
                    //Create deferred object only if you want to manipulate returned data
                }, function (msg, code) {                       
                    console.log(msg, code);
                });
    }

    function methodOne() {
        //DRY
        return get('path/to/data');
    }

    function methodTwo(arg1, arg2) {
        return get('path/to/' + arg1 + '/some/' + arg2 + 'more/data');
    }

    function methodThree(arg1, arg2, arg3) {
        return get('path/to/' + arg1 + '/some/' + arg2 + '/more/' + arg3 + '/data');
    }
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!