我正在尝试为 XHRBackend
类创建一个包装器,我已经能够在我的最外层AppComponent
中成功创建和使用所有提供的服务,但我无法将提供程序打包到实际服务本身中。我正在将类注入组件构造函数中,但我无法想象这会破坏任何东西。
当前AppComponent
代码:
import {HTTP_PROVIDERS, Http, ConnectionBackend, RequestOptions} from "@angular/http";
import {ROUTER_DIRECTIVES} from "@angular/router";
import {XHRBackendWrapper} from 'backendwrapper.services';
@Component({
selector: 'app',
template: './app.component.html',
directives: [ROUTER_DIRECTIVES],
providers: [
HTTP_PROVIDERS,
provide(Http, {
useFactory: (xhrBackend: ConnectionBackend, requestOptions: RequestOptions) => new Http(xhrBackend, requestOptions),
deps: [XHRBackendWrapper, RequestOptions]
}),
XHRBackendWrapper
]
})
export class AppComponent {
constructor(xhrBackend: XHRBackendWrapper){
}
}
所需的AppComponent
代码:
import {HTTP_PROVIDERS} from "@angular/http";
import {ROUTER_DIRECTIVES} from "@angular/router";
import {BACKEND_PROVIDERS, XHRBackendWrapper} from 'backendwrapper.services';
@Component({
selector: 'app',
template: './app.component.html',
directives: [ROUTER_DIRECTIVES],
providers: [
HTTP_PROVIDERS,
/** THIS IS THE ONLY DIFFERENCE HERE!!! ***/
BACKEND_PROVIDERS
]
})
export class AppComponent {
constructor(xhrBackend: XHRBackendWrapper){
}
}
从后端包装器导出的所需常量:
export const BACKEND_PROVIDERS = [
provide(Http, {
useFactory: (xhrBackend: ConnectionBackend, requestOptions: RequestOptions) => new Http(xhrBackend, requestOptions),
deps: [XHRBackendWrapper, RequestOptions]
}),
XHRBackendWrapper
];
当我尝试执行此操作时,我的控制台中出现一个One or more of providers for "AppComponent" were not defined
错误,因为找不到XHRBackendWrapper
。我在这里错过了什么?
我不能发布所有代码,因为它会使这个问题太大,但如果它有帮助,这是XHRBackendWrapper的一般想法:
@Injectable()
export class XHRBackendWrapper extends ConnectionBackend {
constructor(private _xhrBackend: XHRBackend)
{
super();
}
createConnection(request: Request)
{
return this._xhrBackend.createConnection(request);
}
}
不完全确定,但您可能需要像这样解构BACKEND_PROVIDERS:
providers: [
...HTTP_PROVIDERS,
/** THIS IS THE ONLY DIFFERENCE HERE!!! ***/
...BACKEND_PROVIDERS
]