如何在 Angular 2 final 中扩展 angular 2 http class

How to extend angular 2 http class in Angular 2 final

我正在尝试扩展 angular 2 http class 以便能够处理全局错误并为我的 secureHttp 服务设置 headers。我找到了一些解决方案,但它不适用于 Angular 2 的最终版本。 这是我的代码:

文件:secureHttp.service.ts

import { Injectable } from '@angular/core';
import { Http, ConnectionBackend, Headers, RequestOptions, Response, RequestOptionsArgs} from '@angular/http';

@Injectable()
export class SecureHttpService extends Http {

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

文件:app.module.ts

    import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { routing } from './app.routes';
import { AppComponent } from './app.component';
import { HttpModule, Http, XHRBackend, RequestOptions } from '@angular/http';
import { CoreModule } from './core/core.module';
import {SecureHttpService} from './config/secure-http.service'

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    CoreModule,
    routing,
    HttpModule,
  ],
  providers: [
    {
      provide: Http,
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => {
        return new SecureHttpService(backend, defaultOptions);
      },
      deps: [ XHRBackend, RequestOptions]
    }, Title, SecureHttpService],
  bootstrap: [AppComponent],
})
export class AppModule { }

component.ts

constructor(private titleService: Title, private _secure: SecureHttpService) {}

  ngOnInit() {
    this.titleService.setTitle('Dashboard');
    this._secure.get('http://api.example.local')
        .map(res => res.json())
        .subscribe(
            data =>  console.log(data) ,
            err => console.log(err),
            () => console.log('Request Complete')
        );
  }

目前它 returns 我是一个错误 'No provider for ConnectionBackend!'。 感谢您的帮助!

你可以查看https://www.illucit.com/blog/2016/03/angular2-http-authentication-interceptor/这对你有帮助。

如下更改您的提供商以获取最新版本并检查它:

providers: [
  {
    provide: SecureHttpService,
    useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => {
      return new SecureHttpService(backend, defaultOptions);
    },
    deps: [ XHRBackend, RequestOptions]
  },
  Title
]

错误的原因是因为您试图提供 SecureHttpService

providers: [SecureHttpService]

这意味着 Angular 将尝试创建实例,而不是 使用您的工厂。而且它没有使用令牌 ConnectionBackend 注册的提供者来提供给您的构造函数。

您可以从 providers 中删除 SecureHttpService,但这会给您带来另一个错误(我猜这就是您首先添加它的原因)。错误将类似于 "no provider for SecureHttpService" 因为你试图将它注入你的构造函数

constructor(private titleService: Title, private _secure: SecureHttpService) {}

这是您需要了解令牌的地方。您作为 provide 的值提供的是 令牌

{
  provide: Http,
  useFactory: ()
}

令牌是允许我们注入的。因此,您可以改为注入 Http,它将使用 您的 创建的 SecureHttpService。但这将剥夺您使用常规 Http 的任何机会,如果您需要的话。

constructor(private titleService: Title, private _secure: Http) {}

如果您不需要了解SecureHttpService的任何内容,那么您可以这样离开。

如果您希望能够实际注入 SecureHttpService 类型(也许您需要其中的一些 API 或者您希望能够在其他地方使用正常的 Http ),然后只需更改 provide

{
  provide: SecureHttpService,
  useFactory: ()
}

现在您可以同时注入常规 Http 和您的 SecureHttpService。并且不要忘记从 providers.

中删除 SecureHttpService

查看我的 article 关于如何为 Angular 2.1.1

扩展 Http class

首先,让我们创建自定义的 http 提供程序 class。

http.service.ts

import {Injectable} from '@angular/core';
import {Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class HttpService extends Http {

  constructor (backend: XHRBackend, options: RequestOptions) {
    let token = localStorage.getItem('auth_token'); // your custom token getter function here
    options.headers.set('Authorization', `Bearer ${token}`);
    super(backend, options);
  }

  request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
    let token = localStorage.getItem('auth_token');
    if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
      if (!options) {
        // let's make option object
        options = {headers: new Headers()};
      }
      options.headers.set('Authorization', `Bearer ${token}`);
    } else {
    // we have to add the token to the url object
      url.headers.set('Authorization', `Bearer ${token}`);
    }
    return super.request(url, options).catch(this.catchAuthError(this));
  }

  private catchAuthError (self: HttpService) {
    // we have to pass HttpService's own instance here as `self`
    return (res: Response) => {
      console.log(res);
      if (res.status === 401 || res.status === 403) {
        // if not authenticated
        console.log(res);
      }
      return Observable.throw(res);
    };
  }
}

现在,我们需要配置我们的主模块来为我们的自定义 http class 提供 XHRBackend。在您的主模块声明中,将以下内容添加到提供程序数组:

app.module.ts

import { HttpModule, RequestOptions, XHRBackend } from '@angular/http';
import { HttpService } from './services/http.service';
...
@NgModule({
  imports: [..],
  providers: [
    {
      provide: HttpService,
      useFactory: (backend: XHRBackend, options: RequestOptions) => {
        return new HttpService(backend, options);
      },
      deps: [XHRBackend, RequestOptions]
    }
  ],
  bootstrap: [ AppComponent ]
})

之后,您现在可以在您的服务中使用您的自定义 http 提供程序。例如:

user.service.ts

import { Injectable }     from '@angular/core';
import {HttpService} from './http.service';

@Injectable()
class UserService {
  constructor (private http: HttpService) {}

  // token will added automatically to get request header
  getUser (id: number) {
    return this.http.get(`/users/${id}`).map((res) => {
      return res.json();
    } );
  }
}

我认为应该是选择的答案,所以我在这里只是为了扩充他的答案而不是与之竞争,但我也想提供一个具体的例子,因为我不要认为 peeskillet 的答案翻译成什么代码是 100% 明显的。

我将以下内容放在 app.module.tsproviders 部分。我正在调用我的自定义 Http 替换 MyHttp.

请注意,如 peeskillet 所说,它是 provide: Http,而不是 provide: MyHttp

  providers: [
    AUTH_PROVIDERS
    {
      provide: Http,
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => {
        return new MyHttp(backend, defaultOptions);
      },
      deps: [XHRBackend, RequestOptions]
    }
  ],

然后我的Http-extending class定义如下:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class MyHttp extends Http {
  get(url: string, options?: any) {
    // This is pointless but you get the idea
    console.log('MyHttp');
    return super.get(url, options);
  }
}

无需执行任何特殊操作即可让您的应用使用 MyHttp 而不是 Http

您实际上可以在自己的 class 中扩展 Http,然后只使用自定义工厂来提供 Http:

然后在我的 App Provider 中,我可以使用自定义工厂来提供 'Http'

从“@angular/http”导入 {RequestOptions、Http、XHRBackend};

class HttpClient extends Http {
 /*
  insert your extended logic here. In my case I override request to
  always add my access token to the headers, then I just call the super 
 */
  request(req: string|Request, options?: RequestOptionsArgs): Observable<Response> {

      options = this._setCustomHeaders(options);
      // Note this does not take into account where req is a url string
      return super.request(new Request(mergeOptions(this._defaultOptions,options, req.method, req.url)))
    }

  }
}

function httpClientFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions): Http {

  return new HttpClient(xhrBackend, requestOptions);
}

@NgModule({
  imports:[
    FormsModule,
    BrowserModule,
  ],
  declarations: APP_DECLARATIONS,
  bootstrap:[AppComponent],
  providers:[
     { provide: Http, useFactory: httpClientFactory, deps: [XHRBackend, RequestOptions]}
  ],
})
export class AppModule {
  constructor(){

  }
}

使用这种方法,您不需要覆盖任何您不想更改的 Http 函数

从 Angular 4.3 开始,我们不再需要 extends http。相反,我们可以使用 HttpInterceptorHttpClient 来归档所有这些东西。

它与使用 Http 相似且更容易。

我在大约 2 小时内迁移到 HttpClient。

详情为here