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

时间:2016-09-24 11:28:25

标签: angular angular2-services

我试图扩展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的提供商!'。 谢谢你的帮助!

6 个答案:

答案 0 :(得分:22)

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

providers: [SecureHttpService]

这意味着Angular将尝试使用您的工厂创建实例 not 。并且它没有使用令牌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: ()
}

现在您可以注入常规HttpSecureHttpService。不要忘记从SecureHttpService删除providers

答案 1 :(得分: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();
    } );
  }
}

答案 2 :(得分:3)

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

我将以下内容放入providers的{​​{1}}部分。我正在调用我的自定义app.module.ts替换Http

请注意,如peeskillet所说,它将是MyHttp,而不是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,您无需做任何特别的事情。

答案 3 :(得分:2)

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

与使用Http类似且更容易。

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

详情为here

答案 4 :(得分: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
]

答案 5 :(得分:0)

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

然后在我的应用程序提供商中,我能够使用自定义工厂来提供&#39; Http&#39;

从&#39; @ angular / http&#39;;

导入{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函数