Search code examples
javascripthtmlangularjspostget

How to pass method get/post as a function parameter?


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?


Solution

  • 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');