有兩個幾乎相同的功能。第一個函式執行 get()。
function sendGet(url, $http) {
$http
.get(url)
.then(function() {
alert('Ok');
}, function() {
alert('Not Ok');
});
}
第二個帖子()。
function sendPost(url, $http) {
$http
.post(url)
.then(function() {
alert('Ok');
}, function() {
alert('Not Ok');
});
}
是否可以創建更通用的函式,將方法 get/post 作為函式引數傳遞?
function sendGeneric(url, $http, methodCall) {
$http
.methodCall(url)
.then(function() {
alert('Ok');
}, function() {
alert('Not Ok');
});
}
如果是,如何執行這樣的功能?
uj5u.com熱心網友回復:
當然,您可以將所需的函式傳遞給通用函式:
function sendGeneric(url, method) {
method(url)
.then(function() {
alert('Ok');
}, function() {
alert('Not Ok');
});
}
像這樣稱呼它:
sendGeneric(url, $http.post);
sendGeneric(url, $http.get);
或者,對于一些更安全的代碼:
function sendGeneric(url, $http, method) {
$http[method](url)
.then(function() {
alert('Ok');
}, function() {
alert('Not Ok');
});
}
像這樣稱呼它:
sendGeneric(url, $http, 'post');
sendGeneric(url, $http, 'get');
uj5u.com熱心網友回復:
創建一個變數并根據字串設定方法參考methodCall
然后最終執行!
function sendGeneric(url, $http, methodCall) {
const callToMake = methodCall === 'get' ? $http.get : $http.post
callToMake(url).then(function() {
alert('Ok');
}, function() {
alert('Not Ok');
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/507799.html
標籤:javascript html angularjs 邮政 得到