Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

angular - How to override Http class in RC6?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...