自定义 HTTP Class Angular 2 以更改基础 URL 并设置超时
Custom HTTP Class Angular 2 to change base URL and set timeout
您好,我想问一下如何创建自定义 http class 来处理基础 url 并设置默认超时。
我已经在 myhttp 中实现了这个 class:
import { Injectable } from '@angular/core';
import { Http, Request, RequestOptions, ConnectionBackend, RequestMethod, RequestOptionsArgs, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Configuration } from '../config/configuration';
import { PageNavigationService } from './page-navigation.service';
@Injectable()
export class MyHttp extends Http {
serviceBase: string;
timeout: number;
constructor(
backend: ConnectionBackend,
defaultOptions: RequestOptions,
private _pageNavigationService: PageNavigationService) {
super(backend, defaultOptions);
this.serviceBase = Configuration.SERVICE.BASE_URL;
this.timeout = Configuration.SERVICE.TIME_OUT;
console.log('get: ' + this.serviceBase);
}
}
这是我的 main.ts
bootstrap(AppComponent,
[
appRouterProviders,
HTTP_PROVIDERS,
PageNavigationService,
{
provide: Http,
useFactory: (backend: XHRBackend,
defaultOptions: RequestOptions,
_pageNavigationService: PageNavigationService) => new MyHttp(backend, defaultOptions, _pageNavigationService),
deps: [XHRBackend, RequestOptions, PageNavigationService]
}
]).catch(err => console.error(err));
但是没有用,谁能指导一下?
嘿,我已经找到解决办法了
问题是因为我提供了两次HTTP_PROVIDERS
- 在main.ts
- app.component.ts
因此,如果您提供两次,自定义 http 将再次被原始 http 覆盖。
您好,我想问一下如何创建自定义 http class 来处理基础 url 并设置默认超时。
我已经在 myhttp 中实现了这个 class:
import { Injectable } from '@angular/core';
import { Http, Request, RequestOptions, ConnectionBackend, RequestMethod, RequestOptionsArgs, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Configuration } from '../config/configuration';
import { PageNavigationService } from './page-navigation.service';
@Injectable()
export class MyHttp extends Http {
serviceBase: string;
timeout: number;
constructor(
backend: ConnectionBackend,
defaultOptions: RequestOptions,
private _pageNavigationService: PageNavigationService) {
super(backend, defaultOptions);
this.serviceBase = Configuration.SERVICE.BASE_URL;
this.timeout = Configuration.SERVICE.TIME_OUT;
console.log('get: ' + this.serviceBase);
}
}
这是我的 main.ts
bootstrap(AppComponent,
[
appRouterProviders,
HTTP_PROVIDERS,
PageNavigationService,
{
provide: Http,
useFactory: (backend: XHRBackend,
defaultOptions: RequestOptions,
_pageNavigationService: PageNavigationService) => new MyHttp(backend, defaultOptions, _pageNavigationService),
deps: [XHRBackend, RequestOptions, PageNavigationService]
}
]).catch(err => console.error(err));
但是没有用,谁能指导一下?
嘿,我已经找到解决办法了
问题是因为我提供了两次HTTP_PROVIDERS
- 在main.ts
- app.component.ts
因此,如果您提供两次,自定义 http 将再次被原始 http 覆盖。