Joe Conlin
Joe Conlin

Reputation: 5994

Angularjs - What's the correct way for multiple API calls

Ok, please go easy on me as I'm just learning Angular. The following code works but there has to be a better, cleaner, way to do this. I have been reading everything I can and from what I can tell, possibly setting these up in factories might be best?? So far, everything I have tried ends up breaking things but it's probably me doing something incorrectly.

Prerequisites

My code:

$apiUrl = '_includes/gtmetrix.php'; // This is using a local proxy to access remote API.
$apiKey = '';
$gapiUrl = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed';
$gapiKey = '1z2x3c4v5b6n7m8a9s';
$gapiStrategy = 'mobile';
$requestUrl = '<?php echo $_POST['url']; ?>';

function FetchCtrl($scope, $http, $templateCache) {

    $scope.method = 'POST';
    $scope.url = $requestUrl;

    $scope.fetch = function() {
        $scope.code = null;
        $scope.response = null;

        $http({method: $scope.method, url: $apiUrl + '?url=' + $scope.url, cache: $templateCache}).
        success(function(data, status) {
            $scope.status = status;
            $scope.data = data || "Request successful";
        }).
        error(function(data, status) {
            $scope.data = data || "Request failed";
            $scope.status = status;
        });
    };
    $scope.fetch();

    $scope.fetchGoogle = function() {
        $scope.code = null;
        $scope.response = null;

        $http({method: 'GET', url: $gapiUrl + '?url=' + $scope.url + '&key=' + $gapiKey, cache: $templateCache}).
        success(function(data, status) {
            $scope.status = status;
            $scope.datag = data || "Request successful";
        }).
        error(function(data, status) {
            $scope.datag = data || "Request failed";
            $scope.status = status;
        });
    };
    $scope.fetchGoogle();

    $scope.fetchGoogleMobile = function() {
        $scope.code = null;
        $scope.response = null;
        // $scope.data = '<i class="fa fa-spinner fa-spin"></i>';

        $http({method: 'GET', url: $gapiUrl + '?url=' + $scope.url + '&key=' + $gapiKey + '&strategy=' + $gapiStrategy, cache: $templateCache}).
        success(function(data, status) {
            $scope.status = status;
            $scope.datagm = data || "Request successful";
        }).
        error(function(data, status) {
            $scope.datagm = data || "Request failed";
            $scope.status = status;
        });
    };
    $scope.fetchGoogleMobile();

    $scope.updateModel = function(method, url) {
        $scope.method = method;
        $scope.url = url;
    };

}

I have tried to get this working for days now so any help in the right direction would be greatly appreciated. Thx!

Upvotes: 1

Views: 3394

Answers (2)

Darryl
Darryl

Reputation: 1451

Here's what I do. I'm using $resource instead of $http, but it should be enough to get you going. You may even want to use the $resource since it has the built-in functions.

My Factory fns.

.factory('WorkOrder', function($resource){

// $resource Usage: $resource(url[, paramDefaults][, actions]);
return $resource('/controller/get/:id.json', {}, {
    /*
     * By default, the following actions are returned; modify or add as needed
     * { 'get':    {method:'GET'},
     *   'save':   {method:'POST'},
     *   'query':  {method:'GET', isArray:true},
     *   'delete': {method:'DELETE'} };
     */
});

})

My Controller.

// get the work order data using the work order id from the tag attribute
var getWO = function() {

WorkOrder.get({woId:$attrs.id},

    // success callback
    function(response) {
        // Assign the work order data to the scope
        $scope.WorkOrder            = response.WorkOrder;
    },

    // fail callback
    function(response) {
        // whatever...
    }
);
};
getWO();

I put my success and fail fns in my controller because that's where I most likely know how I want to respond to success or failed calls. I also assign the function to a variable and then call it right after in case I want to include the fn call inside a $timeout or call it elsewhere.

You can create as many factory fns as you want. If there's a dependency between factory fn calls, then you can put the dependent call within your success callback of your controller.

Hope this answers your question.

Upvotes: 1

rob
rob

Reputation: 18513

One thing you can do is use the convenient $http.get() and $http.post() methods. Or as Klaster_1 suggested you could look into using $resource. Not sure what your trying to accomplish but it looks like you have some unnecessary code. I might start with something like this and add in more as necessary.

function FetchCtrl($scope, $http) {
    var googleApiBaseUrl = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=<?php echo $_POST['url']; ?>&key=1z2x3c4v5b6n7m8a9s";

    $http.post("_includes/gtmetrix.php?url=<?php echo $_POST['url']; ?>")
        .success(function(data) {
            $scope.data = data;
        });

    $http.get(googleApiBaseUrl)
        .success(function(data) {
            $scope.datag = data;
        });

    $http.get(googleApiBaseUrl + "&strategy=mobile")
        .success(function(data) {
            $scope.datagm = data;
        });
}

Upvotes: 1

Related Questions