There are two almost the same functions. First function executes get().
function sendGet(url, $http) {
$http
.get(url)
.then(function() {
alert('Ok');
}, function() {
alert('Not Ok');
});
}
Second post().
function sendPost(url, $http) {
$http
.post(url)
.then(function() {
alert('Ok');
}, function() {
alert('Not Ok');
});
}
Is it possible to create more generic function which pass method get/post as a function parameter?
function sendGeneric(url, $http, methodCall) {
$http
.methodCall(url)
.then(function() {
alert('Ok');
}, function() {
alert('Not Ok');
});
}
If yes how to execute such function?
CodePudding user response:
Sure, you could just pass the desired function to the generic one:
function sendGeneric(url, method) {
method(url)
.then(function() {
alert('Ok');
}, function() {
alert('Not Ok');
});
}
Call it like this:
sendGeneric(url, $http.post);
sendGeneric(url, $http.get);
Or, for some more secure code:
function sendGeneric(url, $http, method) {
$http[method](url)
.then(function() {
alert('Ok');
}, function() {
alert('Not Ok');
});
}
Call it like this:
sendGeneric(url, $http, 'post');
sendGeneric(url, $http, 'get');
CodePudding user response:
Create a variable and set the method reference based on the string methodCall
then finally execute!
function sendGeneric(url, $http, methodCall) {
const callToMake = methodCall === 'get' ? $http.get : $http.post
callToMake(url).then(function() {
alert('Ok');
}, function() {
alert('Not Ok');
});
}