简体   繁体   中英

angular dynamic attributes for service

Given the following angularjs service:

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);
              });
          }
      };
  } ]);

How can I set the $http.get URL to be dynamic and not hard-coded?

Not sure what part of the url you want to be dynamic, so this is if you want the "term=" + term part to be dynamic:

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);
                });
            }
        };
    } ]);

If you want the actual url that you're posting to be dynamic, pass it in as another parameter:

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);
              });
          }
      };
  } ]);

If neither of these are what you're looking for... can you elaborate on what part of the url you want to be dynamic?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM