簡體   English   中英

服務的角度動態屬性

[英]angular dynamic attributes for service

給定以下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設置為動態且未進行硬編碼?

不確定要動態化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的哪一部分?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM