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

24

我正在尝试扩展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 { }

组件.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个回答

22
错误的原因是您试图提供SecureHttpService。
providers: [SecureHttpService]
这意味着Angular将尝试创建实例,而不使用您的工厂,并且没有针对令牌ConnectionBackend注册的提供者可供传递给构造函数。
您可以从providers中删除SecureHttpService,但这会给您另一个错误(我猜这就是您首先添加它的原因)。错误信息将类似于“无法提供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


我在一年之后重新登录我的账户只为了给这个答案点赞。谢谢! - Stephen Walcher
我在 app.module.ts 中的 {provide: HttpService, useFactory: ()}, 代码处遇到了 "Expression expected." 错误。 - Pavel Chuchuva
@PavelChuchuva 你需要将其提取到一个函数中并使用该函数。这只会在AOT中发生。请参见此帖子中的更新 - Paul Samsotha

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

现在,我们需要配置主模块以向我们的自定义http类提供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();
    } );
  }
}

你有没有测试过自己的代码?无法调用 constructor(..) { statements; super(...); }。当继承另一个类时,super() 必须是第一条语句。 - phil294
我做了。虽然我不知道具体情况,但这段代码是我的应用程序的一部分,并且它是有效的。 - papar
有趣的是,对我来说它并没有起作用。然而,如果super()..放在首位,一切都能完美运行。 - phil294
我得到了一个错误:“1:25 错误:无法解析CoinService的所有参数:(?)。 在CompileMetadataResolver.getDependenciesMetadata()处。理想情况下,“super”应该在更新选项参数之后。 但是对我来说,两者都不起作用。 - NitinSingh
我们在使用这个解决方案和U.T时遇到了一些问题,这是由于使用XhrBackend而不是ConnectionBackend类,导致与MockBackend类不兼容。 - Loenix

3
我认为peeskillet的回答应该成为被选中的答案,因此我在此提供的内容只是为了补充他的答案而不是与之竞争,但我也想提供一个具体的例子,因为我认为peeskillet的回答所转换的代码并不完全明显。

我将以下代码放在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的类定义如下:
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


1
太棒了!运行起来非常顺畅,感觉就像注射器一样。整个应用程序代码也保持不变,他们感觉好像在使用 Http,实际上他们正在使用我们的扩展版本(正如你最后一行所说)。 - NitinSingh
这应该是被选中的答案。谢谢! - Vidal Quevedo

2
自从 Angular 4.3 版本开始,我们不再需要使用 extends http。相反,我们可以使用 HttpInterceptorHttpClient 来完成所有这些工作。
这与使用 Http 相似且更容易。
我在大约两个小时内就迁移到了 HttpClient。
详细信息请参见此处

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
]

嗨,ranakrunal9!我看到了。这是RC1的代码,不适用于最终版本。但无论如何还是谢谢你 :) - mezhik91
你必须更改导入的类的路径,因为在最终发布中可能会更改路径。 - ranakrunal9
导入类的路径是正确的。我已经检查过了。我认为问题可能出现在app.module中的提供者部分...但我不确定... - mezhik91
不行,还是出现了“没有ConnectionBackend的提供程序!”我已经更新了问题并提供了整个app.module文件的代码。也许你会发现一些东西。 - mezhik91
从您的提供程序中删除SecureHttpService,这样就可以消除ConnectionBackend错误。 - ganders

0
你可以在自己的类中扩展 Http,然后只需使用自定义工厂来提供 Http:
然后在我的应用程序提供程序中,我能够使用自定义工厂来提供 'Http'
import { RequestOptions,Http,XHRBackend } from '@angular/http';
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函数


mergeOptions 的定义在哪里? - Lyoneel
@Lyoneel 这是一个基本函数,只是合并选项,没有什么特别的 - 可以查看 Angular 的源代码了解他们的实现 https://github.com/angular/angular/blob/master/modules/%40angular/http/src/http.ts - jonnie
是的,没错。我检查了http.umd.js,它在那儿,只是我的IDE解析不太好。 - Lyoneel
截至今天的Angular4版本,将提供者声明为函数而不是lambda表达式的事实效果更好。谢谢。 - wiwi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接