1

I would like to know whether we can create a provider in angularjs which will replace the $http operation .which means where we can use this provider in other modules where we can make use of these $http operation. The reason why provider has to be taken is because we can configure the http parameters like the api path, request type .

Also can we have logging/exception handling mechanism inside the provider so that the modules(eg: any other factories) which inherit the provider wont need to do any extra logging/exception mechanisms. Is there any way to have some loading screen using this provider when http requests are made ?

1
  • Consider revising the wording in your question it is very difficult to understand what it is your trying to achieve or what is going wrong... try to state your question in a format like: I was trying to achieve X, I did Y and expected Z but instead ABC happened, what went wrong? Commented May 30, 2014 at 4:21

1 Answer 1

4

For the things you mentioned, you don't need another provider, because $http has the concept of interceptors.

Interceptors can specify different callbacks to be executed at different phases:

  • request (runs before any request is sent): It can modify the configuration (e.g. the request URL, method etc). It could also be used to show some loading message/animation (e.g. using some property on the $rootScope).

  • requestError (runs when there is an error before sending the request): It can be used for logging, recovering, exception handling.

  • response (runs after any response is received): It can be used for logging. It could also be used to hide the loading message/animation. (Don't forget to also handle this on response error.)

  • responseError (runs when there is an error regarding the response (e.g. bad request)): It can be used for logging, recovering, exception handling.


If interceptors do not cover your needs, you could use $provide's decorator to monkey-patch, augment or totally replace the $http service:

.config(function ($provide) {
    $provide.decorator('$http', function ($delegate) {
        var newHttp = $delegate;   // or a totally new object
        // ...monkey-patch newHttp or define new methods or whatever
        return newHttp;
    });
});
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.