1

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

  • I need to be able to use this in a module (so I can add additional custom directives I have)
  • I am making a total of 3 API calls, two are using GET method but one has to use POST method

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!

1
  • First of all, you might want to combine requests with $q.all and use only one function for callbacks. There are also an option to abstract API calls with ngResource module. Commented Dec 12, 2013 at 2:45

2 Answers 2

1

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;
        });
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.