How to register a http provider factory in ionic2?


#1

I have to intercept all http calls.


#2

It’s possible on native? If yes, then you could write cordova plugin for it.


#3

Not sure what you mean.
To be more specific in what I want to accomplish: In Angular2 you can add a provider factory as a parameter to the bootstrap() call on startup. This way you can inject i. e. a custom http provider to your application, which is than used everywhere during runtime. I don’t see anything aquivalent to the bootstrap() call in Ionc2. So my question is, what is the right way in ionic2 to add custom providers to the framework?


#4

Have you tried something like:

@App({
  providers: [Http, {useClass: CustomHttp}]
})

#5

Refering to the Angular2 docs (https://angular.io/docs/ts/latest/guide/dependency-injection.html) this should work:

@App({
  providers: [provide(Http, {useClass: CustomHttp})]
})

or

@App({
  providers: [new Provider(Http, {useClass: CustomHttp})]
})

but it doesn’t. At least this should work:

@App({
  providers: [new Provider(Http, {useClass: Http})]
})

What is the Ionic2 way?


#6

I had to use a provider factory for registration. Now it works like a charm. Here is my App Component’s provider property assignment:

 providers: [HTTP_PROVIDERS, 
                provide(Http, {
                        useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) => new HttpInterceptor(xhrBackend, requestOptions),
                        deps: [XHRBackend, RequestOptions]
                    }),
                provide(XHR, { 
                    useFactory: (http: Http) => new XHRInterceptor(http), deps: [Http] 
                })],