你如何在Angular中重用代码?

时间:2018-05-08 20:43:47

标签: angularjs function angular2-directives angular-factory

我有控制器,它可以获取一些数据并根据信息添加一些额外的项目。信息应该是可搜索的。我现在有工作代码,但想知道重用代码的最佳方法是什么?是指令吗?厂?这是代码:

app.controller('searchProducts', function($scope, $http) {
$scope.search = function(val) {
    $scope.val = val;
    //from here
    let query;
    if(!$scope.val) {
        query = BASE_URL+"Products";   
    }
    if($scope.val) {
        query = encodeURI("Products?$filter=contains(ProductName,\'"+val+"\')");
        query = BASE_URL+query;
    }
    $http.get(query)
        .then(function(response) {
            $scope.rawData = response.data;
            angular.forEach($scope.rawData.value, function(value) {
                //looping the data, replacing the IDs with actual data from the source
                //Getting actual Supplier using SupplierID
                $http.get("http://services.odata.org/V4/Northwind/Northwind.svc/Suppliers("+value.SupplierID+")/CompanyName/$value")
                    .then(function(response) {
                        value.Supplier = response.data;           
               })
                //Getting actual Category using CategoryID
                $http.get("http://services.odata.org/V4/Northwind/Northwind.svc/Categories("+value.CategoryID+")/CategoryName/$value")
                    .then(function(response) {
                        value.Category = response.data;           
               })
            });
        })
    //to here
}
    //is repeated here
});

1 个答案:

答案 0 :(得分:2)

您将使用工厂并将该行为捆绑在一个或多个方法中,即

app.factory('myFactory', function($http, $q) {
    return {
        myRequest: function(query) {
            return $http.get(query).then(this.myHandler);
        },
        myHandler: function(response) {
            var categoryPromises = [];
            var supplierPromises = [];
            angular.forEach(response.data, function(value) {
                supplierPromises.push($http.get("http://services.odata.org/V4/Northwind/Northwind.svc/Suppliers("+value.SupplierID+")/CompanyName/$value"));
                categoryPromises.push($http.get("http://services.odata.org/V4/Northwind/Northwind.svc/Categories("+value.CategoryID+")/CategoryName/$value"));
            });
            return $q.all([$q.all(supplierPromises), $q.all(valuePromises)]);
        }
    };
});
// and to invoke the factory
app.controller('myController', function(myFactory) {
    myFactory.myRequest('/path/to/resource')
        .then(function(results) {
            //... handle your results
        })
        .catch(function(e) {
            throw e;
        });
});