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

问题描述 投票:24回答:6

我正在尝试扩展angular 2 http类,以便能够处理全局错误并为我的secureHttp服务设置标头。我找到了一些解决方案,但它不适用于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')
        );
  }

现在它返回一个错误'没有ConnectionBackend的提供者!'。感谢帮助!

angular angular2-services
6个回答
22
投票

出错的原因是因为您正在尝试提供SecureHttpService

providers: [SecureHttpService]

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

你可以从SecureHttpService中删除providers,但这会给你另一个错误(我猜你是为什么你首先添加它)。错误将类似于“没有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。并且不要忘记从SecureHttpService中删除providers


21
投票

查看我的article,了解如何扩展Angular 2.1.1的Http类

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

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类提供XHRBackend。在主模块声明中,将以下内容添加到providers数组:

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

3
投票

我认为peeskillet's answer应该是选定的答案,所以我放在这里只是为了增加他的答案而不是与之竞争,但我也想提供一个具体的例子,因为我不认为它是100%明显的什么代码peeskillet的答案转化为。

我把以下内容放在我的providersapp.module.ts部分。我叫我的自定义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扩展类定义如下:

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


2
投票

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

它比使用Http更类似,更容易。

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

细节是here


0
投票

你可以检查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
]

0
投票

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

然后在我的应用程序提供商中我能够使用自定义工厂提供'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函数

© www.soinside.com 2019 - 2024. All rights reserved.