1

给定以下 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 URL 设置为动态而不是硬编码?

4

1 回答 1

0

不确定你想要动态的 url 的哪一部分,所以如果你想让 "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);
              });
          }
      };
  } ]);

如果这些都不是您要查找的内容...您能否详细说明您想要动态的 url 的哪一部分?

于 2012-12-24T17:10:06.073 回答