0

I want to use Google Analytics for all of my requests. I am using $http and $resource and my application is too big, so I don't want to create any wrapper function. Is there way, in AngularJS 1.4.5, that I can track all requests and apply some Google Analytics?

1 Answer 1

1

You can use an interceptor. By implementing the interceptor API and pushing it into the $httpProviders interceptor array. If implemented properly, you can handle every request/response in a centralized manner.

Here's a sample using TypeScript and class syntax:

class ErrorInterceptor {

    static $inject = ['$q'];
    constructor(private $q: ng.IQService) {}

    public request = (config) => {
        // Do something on success
        return config;
    }

    public requestError = (rejection) => {
        // Do something on error
        return this.$q.reject(rejection);
    }

    public response = (response) => {
        // Do something on success
        return response;
    }

    public responseError = (responseFailure) => {
        // Do something on error
        // Handle error codes separately if needed, e.g.:

        if (responseFailure.status === -1) {

        } else if (responseFailure.status === 401) {

        } else if (responseFailure.status === 403) {

        } else if (responseFailure.status === 404) {

        } else if (responseFailure.status === 500) {

        } else if (responseFailure.status === 503) {

        } else {

        }

        return this.$q.reject(responseFailure);
    }
}

const ErrorInterceptorConfig = ['$httpProvider', ($httpProvider) => {
    $httpProvider.interceptors.push('ErrorInterceptor');
}];

// Register the service and configuration:
angular.module('yourModule')
    .service('ErrorInterceptor', ErrorInterceptor)
    .config(ErrorInterceptorConfig);

As shown in the documentation linked above, you can also do this using an anonymous factory:

angular.module('yourModule')
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.interceptors.push(['$q', function($q) {
            return {
                request: function(config) { ... },
                response: function(response) { ... },
                ...
            }
        }]);
    }]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.