服务的角度动态属性

时间:2012-12-24 16:39:11

标签: javascript angularjs

给出以下angularjs服务:

angular.module('myApp.services', [])
  .factory('EmployeesService', ['$http', function ($http) {
      return {
          name: 'Employees Service',
          getByTerm: function (term, callback) {
              $http.get('Services/GetEmployess?term='+term).success(function (data) {
                  callback(data);
              });
          }
      };
  } ]);

如何将$ http.get网址设置为动态而非硬编码?

1 个答案:

答案 0 :(得分:0)

不确定您想要动态的网址的哪一部分,所以如果您希望“term =”+ term部分是动态的:

angular.module('myApp.services', [])
    .factory('EmployeesService', ['$http', function ($http) {
        return {
        name: 'Employees Service',
        getByTerm: function (params, callback) {
                var terms = [];

                //params example: {param1: "lorem", param2:"ipsum"}
                for(var key in params){
                    if(params.hasOwnProperty(key)){
                        terms.push(key + "=" + params[key]);
                    }
                }
                //terms now looks like this: ["param1=lorem", "param2=ipsum"]

                var url = 'Services/GetEmployess?' + terms.join("&");

                //url will look lik this: 'Services/GetEmployess?param1=lorem&param1=ipsum';

                $http.get(url).success(function (data) {
                    callback(data);
                });
            }
        };
    } ]);

如果您希望发布的实际网址是动态的,请将其作为另一个参数传递:

angular.module('myApp.services', [])
  .factory('EmployeesService', ['$http', function ($http) {
      return {
          name: 'Employees Service',
          getByTerm: function (url, term, callback) {
              $http.get(url+term).success(function (data) {
                  callback(data);
              });
          }
      };
  } ]);

如果这些都不是你想要的......你能详细说明你想要动态的网址的哪一部分吗?

相关问题