Greetings, I am new to Angular and seeking guidance on optimizing the following code snippet. While it does function as intended, I believe there must be a more efficient approach. I've delved into various resources and it seems structuring these tasks within factories could be beneficial. However, my attempts thus far have resulted in errors, likely due to my own oversight.
Essential Requirements
- I require compatibility within a module (to incorporate custom directives)
- The functionality involves 3 API calls: 2 via GET method, while one necessitates POST method usage
Snippet Overview:
$apiUrl = '_includes/gtmetrix.php'; // Utilizing a local proxy for remote API access.
$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 been grappling with this setup for quite some time now, so any assistance or pointers would be highly valued. Thank you!