如何将get/post方法作为函数参数传入以实现通用请求函数?
通用HTTP请求函数实现方案
你现有两个逻辑几乎完全重复的HTTP请求函数:
GET请求函数
function sendGet(url, $http) { $http .get(url) .then(function() { alert('Ok'); }, function() { alert('Not Ok'); }); }
POST请求函数
function sendPost(url, $http) { $http .post(url) .then(function() { alert('Ok'); }, function() { alert('Not Ok'); }); }
当然可以创建通用函数,但你写的sendGeneric存在问题:直接使用.methodCall(url)会把methodCall当作$http的固定属性名,而非你传入的方法引用。以下是两种正确的实现方式:
方式一:传入方法名称字符串
通过方括号语法访问$http的对应方法,这是最直观的实现:
function sendGeneric(url, $http, methodName) { $http[methodName](url) .then(function() { alert('Ok'); }, function() { alert('Not Ok'); }); }
调用示例:
// 发起GET请求 sendGeneric('/api/fetch-data', $http, 'get'); // 发起POST请求 sendGeneric('/api/submit-form', $http, 'post');
方式二:直接传入方法引用
直接把$http.get或$http.post作为函数参数传入,需要用call绑定上下文,或者通过方法名访问:
function sendGeneric(url, $http, method) { // 使用call绑定$http作为上下文 method.call($http, url) .then(function() { alert('Ok'); }, function() { alert('Not Ok'); }); }
或者更简洁的写法:
function sendGeneric(url, $http, method) { $http[method.name](url) .then(function() { alert('Ok'); }, function() { alert('Not Ok'); }); }
调用示例:
// 发起GET请求 sendGeneric('/api/fetch-data', $http, $http.get); // 发起POST请求 sendGeneric('/api/submit-form', $http, $http.post);
两种方式都能实现代码复用,你可以根据自己的编程习惯选择。
内容的提问来源于stack exchange,提问作者John Friday
相关产品推荐
相关产品推荐

