【问题标题】:AngularJS Best Practice - Factory with multiple methodsAngularJS 最佳实践 - 具有多种方法的工厂
【发布时间】:2021-08-11 22:26:00
【问题描述】:

我有一个提供三种不同$http.get 方法的工厂。

angular.module('myApp')
	.factory('getFactory', function ($http, $q) {

	return {

		methodOne: function () {
			var deferred  = $q.defer();

			$http.get('path/to/data')
				.then(function successCallback (data) {
    					deferred.resolve(data);
    				},function errorCallback (response) {
                                        console.log(response);
                                });

			return deferred.promise;
		},

		methodTwo: function (arg1, arg2) {
			var deferred  = $q.defer();

			$http.get('path/to/' + arg1 + '/some/' + arg2 + 'more/data')
				.then(function successCallback (data) {
    					deferred.resolve(data);
    				},function errorCallback (response) {
                                        console.log(response);
                                });

			return deferred.promise;
		},

		methodThree: function (arg1, arg2, arg3) {
			var deferred  = $q.defer();

			$http.get('path/to/' + arg1 + '/some/' + arg2 + '/more/' + arg3 + '/data')
				.then(function successCallback (data) {
    					deferred.resolve(data);
    				},function errorCallback (response) {
                                        console.log(response);
                                });

			return deferred.promise;
		},
	};
	});

基本上,这些方法仅在获取数据的路径上有所不同。这些方法获得的数据在控制器中处理。我一直在阅读大量 Angular 最佳实践,并且看到了 DRY(不要重复自己)提示。

我觉得我上面的代码太重复了。有没有更好的方式来编码这种Angular 方式

**注意:我使用 yeoman 生成器来搭建我项目的目录。

【问题讨论】:

  • AFAIK successerror 已弃用,您应该使用 then insetad。
  • @AlexanderBondar 感谢您的通知。我刚刚在AngularJS $http documentation 上阅读了它。将编辑代码。

标签: javascript angularjs angularjs-factory


【解决方案1】:
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');
    }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多