【问题标题】:Angular 2 custom http service throws Error: No provider for XHRBackendAngular 2 自定义 http 服务抛出错误:XHRBackend 没有提供者
【发布时间】:2017-09-12 00:32:32
【问题描述】:

我想创建自己的 http 服务,以便可以像使用 http 拦截器一样使用它,但我收到一个很长的错误,开头为:EXCEPTION: Uncaught (in promise): Error: No provider for XHRBackend!

http.service.ts

import { Injectable } from '@angular/core';
import { Http, XHRBackend, RequestOptions, RequestOptionsArgs, Request, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';


@Injectable()
export class HttpService extends Http {
    constructor(backend: XHRBackend, options: RequestOptions) {
        console.log('HttpService constructor');
        super(backend, options);
    }

    request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
        console.log('HttpService request');
        return super.request(url, options);
    }    
}

export const HTTP_SERVICE = {
    provide: HttpService,
    useFactory: (backend: XHRBackend, options: RequestOptions) => {
        return new HttpService(backend, options);
    },
    deps: [XHRBackend, RequestOptions]
};

然后我将它添加到 app.module.ts 中

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { AuthService } from './auth/auth.service';
import { HTTP_SERVICE } from './shared/http/http.service';

@NgModule({
    imports: [
        BrowserModule,
        AppRoutingModule
    ],
    declarations: [
        AppComponent
    ],
    providers: [
        AuthService,
        HTTP_SERVICE
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

但是当我将它注入组件中的构造函数时它不起作用。我收到了提到的错误。

我还读到我可以做到:

{ provide: Http, useClass: HttpService}

来自此博客:http://www.adonespitogo.com/articles/angular-2-extending-http-provider/

但这也行不通。在这里我没有错误,但没有什么不同。正如我对代码所期望的那样,我没有得到控制台的输出。

我还尝试添加 HttpService,因为它在提供程序数组中,但仍然出现该错误。

【问题讨论】:

  • 您可以将HttpModule 添加到imports 以获取它已经定义的提供程序。那么您就不需要HTTP_SERVICE 并且可以只使用博客中的简单提供程序。
  • 我有同样的问题,但没有解决方案,你找到了吗?
  • 在导入中添加 httpModule 将解决此问题

标签: angular


【解决方案1】:

正如Mukul Jayaprakash 所说,在您的imports 中添加httpModule 将解决此问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 2023-04-09
    • 2017-02-21
    • 2017-02-14
    • 2017-01-22
    • 1970-01-01
    • 2017-08-22
    相关资源
    最近更新 更多