Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override Http class in RC6?

Tags:

angular

I have CustomHttp class and I use it to add headers to my get requests:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { RequestOptionsArgs, RequestOptions, ConnectionBackend, Http, Request, Response, Headers } from "@angular/http";

@Injectable()
export class CustomHttp extends Http {

headers: Headers = new Headers({ 'Something': 'Something' });
options1: RequestOptions = new RequestOptions({ headers: this.headers });

constructor(backend: ConnectionBackend,
    defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
}

get(url: string, options?: RequestOptionsArgs) {
    console.log('Custom get...');
    return super.get(url, this.options1).catch(err => {
        console.log(err);
        if (err.status === 404) {
            console.log('404 error');
            return Observable.throw(err);
        }
    });
    }
}

In RC5, I added it to my AppModule providers like this:

provide (Http, {
            useFactory: (
                backend: XHRBackend,
                defaultOptions: RequestOptions) =>
                new CustomHttp(backend, defaultOptions),
            deps: [XHRBackend, RequestOptions]
        })

But, in RC6, provide from @angular/core is deprecated and I'm having problems adding my CustomHttp class to AppModule providers. Does anyone have an idea how to do this?

like image 403
Stefan Svrkota Avatar asked Sep 02 '16 07:09

Stefan Svrkota


1 Answers

The syntax has change a bit, besides that it should still work the same:

    { provide: Http, 
        useFactory: (
            backend: XHRBackend,
            defaultOptions: RequestOptions) =>
            new CustomHttp(backend, defaultOptions),
        deps: [XHRBackend, RequestOptions]
    }
like image 134
Günter Zöchbauer Avatar answered Nov 20 '22 07:11

Günter Zöchbauer