问题描述
我需要获取Http实例而不使用Angular2的DI(构造函数(私有http:Http))
I need to get an instance of Http without using Angular2's DI ( constructor(private http: Http) )
以下代码摘自另一个stackoverflow问题,并且它可以在Angular2 RC.4和更早的版本中使用,但在RC.5 +中不可用(HTTP_PROVIDERS不再可用):
The following code was taken from another stackoverflow question, and it works in Angular2 RC.4 and earlier versions, but not in RC.5+(HTTP_PROVIDERS is no longer available) :
const injector = ReflectiveInjector.resolveAndCreate([
HTTP_PROVIDERS
]);
this.http = injector.get(Http);
关于Stackoverflow,这里有几个问题,它们具有相同代码的不同变体,但它们都无法在RC.5 +中使用.
There are several questions here on Stackoverflow with different variants of that same code, but none of them works in RC.5+.
有人知道如何在RC.5 +中执行相同的操作吗?
Does anybody know of how to perform that same thing in RC.5+?
推荐答案
只需查看 HttpModule
.您将看到创建Http
所需的所有提供程序.这些提供商中的大多数都是现在已删除的HTTP_PROVIDERS
Just look at the source for HttpModule
. You'll see all the providers required to create the Http
. Most of those providers were what were in the now removed HTTP_PROVIDERS
export function _createDefaultCookieXSRFStrategy() {
return new CookieXSRFStrategy();
}
export function httpFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions): Http {
return new Http(xhrBackend, requestOptions);
}
@NgModule({
providers: [
{provide: Http, useFactory: httpFactory, deps: [XHRBackend, RequestOptions]},
BrowserXhr,
{provide: RequestOptions, useClass: BaseRequestOptions},
{provide: ResponseOptions, useClass: BaseResponseOptions},
XHRBackend,
{provide: XSRFStrategy, useFactory: _createDefaultCookieXSRFStrategy},
],
})
export class HttpModule {
}
只需将上述providers
中的所有内容添加到传递给ReflectiveInjector.resolveAndCreate
的数组中即可.
Just add everything in the above providers
to the array you pass to ReflectiveInjector.resolveAndCreate
.
如果您的目标是在引导之前获取Http
,则还需要注意另一件事,那就是CookieXSRFStrategy
.它在引导之前将不起作用,因为它依赖于某些平台浏览器的内容.您可以将其替换为noop,如此帖子
If your goal is to get the Http
before bootstrap, there's another little thing you need to take care of, which is the CookieXSRFStrategy
. It will not work prior to bootstrapping, as it is dependendent on some platform browser stuff. You can just replace it with a noop, as mentioned in this post
这篇关于如何在不使用构造函数DI的情况下创建Http实例? (RC.5 +)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!