Angular2提供自定义Http不工作

时间:2016-09-09 21:30:04

标签: angular angular2-http

我们需要一个全球空间来捕获http 401,403和500个响应。我查看了一些教程并尝试了扩展http的方法。这是我的自定义HTTP(主要是从在线复制)

import { Http, ConnectionBackend, Request, RequestOptions, RequestOptionsArgs, Response, Headers} from '@angular/http';
import { Router} from '@angular/router';
import { Injectable} from '@angular/core';
import { Observable} from 'rxjs/Rx';

@Injectable()


export class CustomHttp extends Http {

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _router : Router) {
        super(backend, defaultOptions);
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.request(url, options));
    }

    get(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.get(url, options));
    }

    post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.post(url, body, this.getRequestOptionArgs(options)));
    }

    put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.put(url, body, this.getRequestOptionArgs(options)));
    }

    delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.delete(url, options));
    }

    getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
        if (options == null) {
            options = new RequestOptions();
        }
        if (options.headers == null) {
            options.headers = new Headers();
        }
        options.headers.append('Content-Type', 'application/json');
        return options;
    }

    intercept(observable: Observable<Response>): Observable<Response> {
        return observable.catch((err, source) => {
            console.log('CustomHttp Error status:  ' + err.status);
            return Observable.throw(err); 
        });
    }

}

以下是我如何引导我的应用并尝试使用我的实现替换默认HTTP:

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
import { HTTP_PROVIDERS, Http, XHRBackend, RequestOptions} from '@angular/http';
import { ROUTER_DIRECTIVES, Router } from '@angular/router';
import { APP_ROUTER_PROVIDERS  } from './app.routes';
import { provide, PLATFORM_DIRECTIVES} from '@angular/core';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { CustomHttp } from './utils/http/customhttp';


    bootstrap(AppComponent, [
        APP_ROUTER_PROVIDERS,
        HTTP_PROVIDERS,
        provide(LocationStrategy, { useClass: HashLocationStrategy }),
        provide(PLATFORM_DIRECTIVES, { useValue: [ROUTER_DIRECTIVES], multi: true }),
        provide( Http, {
            useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, router: Router) => new CustomHttp(xhrBackend, requestOptions, router),
            deps: [XHRBackend, RequestOptions, Router]
        }),
    ]);

没有编译错误但是当我尝试使用默认提供程序而不是我的实现来创建一些http请求时。我知道这是因为我故意调用一个返回500的webapi端点,并且不设置为我的catch子句并写一个日志语句。

以下是我的js依赖:

 "dependencies": {
    "@angular/common": "2.0.0-rc.4",
    "@angular/compiler": "2.0.0-rc.4",
    "@angular/core": "2.0.0-rc.4",
    "@angular/forms": "0.2.0",
    "@angular/http": "2.0.0-rc.4",
    "@angular/platform-browser": "2.0.0-rc.4",
    "@angular/platform-browser-dynamic": "2.0.0-rc.4",
    "@angular/router": "3.0.0-beta.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.4",

    "systemjs": "0.19.27",
    "core-js": "^2.4.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",

    "lodash": "4.13.1",
    "angular2-in-memory-web-api": "0.0.14",
    "bootstrap": "^3.3.6"
  }

我在这里缺少什么胶水?

2 个答案:

答案 0 :(得分:1)

确保您没有在某个组件上提供HTTP_PROVIDERSHttp,否则可能会改为使用(取决于提供的确切位置)。

答案 1 :(得分:0)

这对我有用。我不得不配置我的基本服务网址。当我在本地运行以及部署到prod服务器时,它应该检测环境。

@Injectable()
export class HttpService extends Http {

  static SERVICE_BASE_URL = '';

  constructor(backend: XHRBackend, options: RequestOptions) {
    super(backend, options);

    if (/http:\/\/(localhost|127.0.0.1)/.test(window.location.href)) {
      HttpService.SERVICE_BASE_URL = 'http://localhost:8000';
    } else {
      HttpService.SERVICE_BASE_URL = 'http://mywebsite.com/api';
    }
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return super.get(this.toTargetUrl(url), options);
  }

  post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return super.post(this.toTargetUrl(url), body, options);
  }

  put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return super.put(this.toTargetUrl(url), body, options);
  }

  delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return super.delete(this.toTargetUrl(url), options);
  }

  toTargetUrl(url: string): string {
    return url = /^https?:/.test(url) ? url : HttpService.SERVICE_BASE_URL + url;
  }
}

这是我在app.module.ts

中配置的方式
providers: [
    {
        provide: Http,
        useFactory: HttpFactory,
        deps: [XHRBackend, RequestOptions]
    },
    UtilsProvider,
    LocalStorageProvider
]

export function HttpFactory(backend: XHRBackend, options: RequestOptions) {
    return new HttpService(backend, options);
}