如何将params传递给AngularJS工厂

时间:2014-02-16 08:41:26

标签: angularjs angular-resource

我对Angular很新,但是我试图将REST $从$ http抽象到工厂/资源,但我似乎无法将任何参数传递给它。虽然我读过但是找不到这个例子。

我的工厂代码(services.js):

myApp.factory("PropertyDb", function($resource, $log) {
return {
    getProperties: function(onSuccess) {
        var properties = $resource("http://myurl.com/get_properties.php?", {
            callback: 'JSON_CALLBACK',
            postcode: 'AA11AA',
            minimum_beds: '3',
            minimum_price: '97500'
        }, 

        {
            fetch : {method:'JSONP'},
            params: {postcode: 'BB11BB'} // This doesn't override the above or work without the above postcode

        });

        properties.fetch(
            function success(response) {
                console.log(response);
                onSuccess(response.listing);
            }, 
            function error(response) {
                console.log(response);
                console.log("error");
            }
        );
    },

我的控制器代码:

myControllers.controller('PropertyListCtrl', ['$scope', 'PropertyDb',
function($scope, PropertyDb) {

    $scope.properties = {};

    // Adding the postcode below doesnt work...
    PropertyDb.getProperties({postcode : 'CC11CC'}, function(responce) {
        $scope.properties = responce;
    });

}]);

我希望能够在我的控制器中使用我的工厂并将其传递给不同的参数,例如邮政编码等,并覆盖工厂中设置的默认值。无论我尝试什么,我似乎都无法做到这一点,文档也不容易理解。

3 个答案:

答案 0 :(得分:6)

从您的示例中,您将2个参数传递给PropertyDb.getProperties

  • postcode对象:{postcode : 'CC11CC'}
  • 回调:function(responce) {$scope.properties = responce;}

一件事是在工厂使用第一个参数:

myApp.factory("PropertyDb", function($resource, $log) {
return {
    getProperties: function(parameter, onSuccess) {
    //                       ^param^ , ^callback^         

    /* ...  */
    }

所以固定版本的服务应该是:

myApp.factory("PropertyDb", function($resource, $log) {
return {
    getProperties: function(parameter, onSuccess) {
        var properties = $resource("http://myurl.com/get_properties.php?", {
            callback: 'JSON_CALLBACK',
            postcode: parameter.postcode,
            minimum_beds: '3',
            minimum_price: '97500'
        }, 

        {
            fetch : {method:'JSONP'},
            params:  parameter 
        });

        properties.fetch(
            function success(response) {
                console.log(response);
                onSuccess(response.listing);
            }, 
            function error(response) {
                console.log(response);
                console.log("error");
            }
        );
    },
     /*...*/
   }
});

答案 1 :(得分:1)

尝试:

myApp.factory("PropertyDb", function($resource, $log) {
return {
    getProperties: function(data,onSuccess) { //add 1 more parameter
        var properties = $resource("http://myurl.com/get_properties.php?", {
            callback: 'JSON_CALLBACK',
            postcode: 'AA11AA',
            minimum_beds: '3',
            minimum_price: '97500'
        }, 
        {  //fix your code here
            fetch : {
             params: data || {postcode: 'BB11BB'},
             method:'JSONP'
            }
        });

        properties.fetch(
            function success(response) {
                console.log(response);
                onSuccess(response.listing);
            }, 
            function error(response) {
                console.log(response);
                console.log("error");
            }
        );
    },

但我认为更好的解决方案是我们只定义$资源一次:

myApp.factory("PropertyDb", function($resource, $log) {
    //define only once here so we don't need to redefine it whenever we run the method.
    var properties = $resource("http://myurl.com/get_properties.php?", {
                callback: 'JSON_CALLBACK',
                postcode: 'AA11AA',
                minimum_beds: '3',
                minimum_price: '97500'
            }, 
            {  //fix your code here
                fetch : {
                 params: {postcode: 'BB11BB'},
                 method:'JSONP'
                }
            });

    return {
        getProperties: function(data,onSuccess) { //add 1 more parameter

            properties.fetch(
                data, //send the data.
                function success(response) {
                    console.log(response);
                    onSuccess(response.listing);
                }, 
                function error(response) {
                    console.log(response);
                    console.log("error");
                }
            );
        },

答案 2 :(得分:0)

我知道了,您可以使用app.factory()作为单独的js文件来读取文件,比如 get_data.js 。 参数arg是文件路径(现在是一个Web文件,您可以将其更改为相对文件路径,如js/abc.txt)。



var app = angular.module('app', []);

// this part can separate from others as a single file - get_data.js
app.factory('metdata', ['$http', function ($http) {
  var load_data = {};  // This is like a new class in factory
  load_data.getDataPath = function (arg) {  // This is like a method of class
    console.log(arg);
    load_data.path = arg;  // This is like a attribute of class
      return $http.get(load_data.path);
  };
  console.log('print 1 ' + load_data.data);

  return load_data;  // Call the class, and then call getDataPath function

}]); 

app.controller('MainCtrl', ['$scope', 'metdata', function($scope, metdata) {
  $scope.loadData = function () {
    var dataPath = 'https://raw.githubusercontent.com/OnlyBelter/learnGit/master/readme.txt';
    metdata.getDataPath(dataPath).success(function (data) {
      console.log(data);
    });
  };
}]);

<!--this is html file-->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<body ng-app="app" ng-controller="MainCtrl">
    <br>
    <div>
        <p>Load data:
            <button ng-click="loadData()">Load</button>
        </p>
    </div>
</body>
&#13;
&#13;
&#13;