This question already has an answer here:
I need to get an instance of Http without using Angular2's DI ( constructor(private http: Http) )
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);
There are several questions here on Stackoverflow with different variants of that same code, but none of them works in RC.5+.
Does anybody know of how to perform that same thing in RC.5+?
Just look at the source for
HttpModule
. You'll see all the providers required to create theHttp
. Most of those providers were what were in the now removedHTTP_PROVIDERS
Just add everything in the above
providers
to the array you pass toReflectiveInjector.resolveAndCreate
.If your goal is to get the
Http
before bootstrap, there's another little thing you need to take care of, which is theCookieXSRFStrategy
. 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 postFinally found an answer.
You can use Injector to get dependency as shown below.
service.ts
If you still have any doubt, you can check this working plunker made in Angular2.0.0 :
https://plnkr.co/edit/eWLB2BaL66pnJ7SC6qAL?p=preview