如何在RC6中覆盖Http类?

时间:2016-09-02 07:44:59

标签: angular

我有CustomHttp个类,我用它来为我的get个请求添加标题:

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);
        }
    });
    }
}

在RC5中,我将其添加到我的AppModule提供商中,如下所示:

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

但是,在RC6中,provide中的@angular/core已被弃用,我在将CustomHttp类添加到AppModule提供程序时遇到问题。有没有人知道如何做到这一点?

1 个答案:

答案 0 :(得分:6)

语法有所改变,除此之外它应该仍然有效:

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