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

mez*_*k91 24 angular2-services angular

我正在尝试扩展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);
  }
}
Run Code Online (Sandbox Code Playgroud)

文件: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 { }
Run Code Online (Sandbox Code Playgroud)

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')
        );
  }
Run Code Online (Sandbox Code Playgroud)

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

Pau*_*tha 22

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

providers: [SecureHttpService]
Run Code Online (Sandbox Code Playgroud)

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

您可以删除SecureHttpServiceproviders,但会给你另一个错误(我猜是你为什么摆在首位添加的话).错误将类似于"没有SecureHttpService的提供者",因为您试图将其注入构造函数中

constructor(private titleService: Title, private _secure: SecureHttpService) {}
Run Code Online (Sandbox Code Playgroud)

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

{
  provide: Http,
  useFactory: ()
}
Run Code Online (Sandbox Code Playgroud)

令牌是我们允许注入的.所以你可以改为注入Http它,它将使用创建的SecureHttpService.但是Http如果你需要它,这将带走你使用常规的任何机会.

constructor(private titleService: Title, private _secure: Http) {}
Run Code Online (Sandbox Code Playgroud)

如果您不需要了解任何有关的内容SecureHttpService,那么您可以这样做.

如果你想能够实际注入SecureHttpService类型(也许你需要一些API,或者你希望能够在Http其他地方使用法线),那么只需更改provide

{
  provide: SecureHttpService,
  useFactory: ()
}
Run Code Online (Sandbox Code Playgroud)

现在你可以注射常规Http和你的SecureHttpService.而且不要忘了删除SecureHttpServiceproviders.


Ado*_*ogo 21

查看我的文章,了解如何扩展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);
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,我们需要配置我们的主模块,以便为我们的自定义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 ]
})
Run Code Online (Sandbox Code Playgroud)

之后,您现在可以在服务中使用自定义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();
    } );
  }
}
Run Code Online (Sandbox Code Playgroud)