简体   繁体   中英

Assigning value to variable passed to function as parameter

I have several functions declared that each make an API call. Each function is exactly the same in function and I am trying to refactor them all into 1 function to make the code more efficient obviously. For the refactored function I pass in relevant information eg API URL, array to store returned JSON data to etc. The function does a $http request and returns a JSON.

A sample of the JSON is below.

[{
    "options": [{
        "id": "1",
        "desc": "JCB"
    }, {
        "id": "2",
        "desc": "Tractor"
    }, {
        "id": "3",
        "desc": "Truck"
    }]
}]

First I initialize an array to store the returned API JSON to and then make the function call. The initialization and function call looks as follows:

$scope.valuesAPIData = []; // Array to store API JSON
getAPIData("1234", "http://myAPI/getSomeValue.php?userid=", $scope.valuesAPIData, "options"); // Function call passing parameters

I create the function, and my response.data from the $http request returns the JSON data. Checking the apiArray shows the apiArray contains the JSON [object Object] .

1. However, I need to set my initialised array $scope.valuesAPIData to the apiArray . But how do I set $scope.valuesAPIData = apiArray short of writing it as the passed parameters will change on each call. $scope.valuesAPIData is set to nothing (blank) in the alert() below.

2. Also, when I try and query the inner forEach loop with value.apiValue - it returns undefined . When I hard code this as value.options I can access the options - but the problem is that the name of "options" will change in each API call - eg it may be called access in some API calls.

function getAPIData(userID, apiURL, apiArray, apiValue) 
{
    $http.get(apiURL + userID).then(function success(response)
    {
        apiArray = response.data; // apiArray = [object Object]
        alert("$scope.valuesAPIData: " + $scope.valuesAPIData); // Nothing here (blank)

        angular.forEach(apiArray, function (value, key)
        {
            angular.forEach(value.apiValue, function (v, k) // value.apiValue gets missed completely
            {
                alert("API Response Data - id: " + v.id); 
                alert("API Response Data - desc: " + v.desc);
            });
        });
    },
    function error(response) 
    {
        var data = response.data;
        alert("A error has occurred.");
    });      
}

The best approach for this type of Api Calls function is to let who ever called the function to handle the result. And if you need to do some parsing so it better to do it in the api function . This way you will be able to call the function from various of entities (Components,Controllers,Other services)

var apiFunction  = (path,id) => {
    return $http.get(path + id).then(result => result);
}

and you call it (let say from your controller)

someService.apiFunction('example','234').then(result => {
    //do what ever logic you want for example
    $scope.result = result;

})

and if you want to parse the data before return it to the function callee

var apiFunction = (path,id) =>{ 
    return $http.get(path+id).then(result => {
        let parser = []
        result.data.forEach((item) =>{
           //assign whatever you want for example 
           if(item['options']) {
             //stuff here                
           }  
           else if(item['somethingelse']){
             //stuff here
           }
        })
        //will return parser as result to the callee entity  
        return parser; 
    })      
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM