[英]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¶m1=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.