angular2 resolveAndCreate HTTP - missing HTTP_PROV

2019-01-09 19:24发布

问题:

back in RC4 when HTTP_PROVIDERS existed I could create my custom http instance using

export function createHTTP(url:string, headers?:Headers){
  let injector = ReflectiveInjector.resolveAndCreate([
    myHttp,
    {provide:'defaultUrl', useValue:url},
    {provide:'defaultHeaders', useValue:headers || new Headers()},
    ...HTTP_Providers
  ])
  return injector.get(myHttp)
}

myHttp was a wrapper for Http

@Injectable()
export class myHttp{
  constructor(@Inject('defaultUrl) private url:string, @Inject('defaultHeaders) private headers:Headers, private http:Http){}

  get()
  put()...
}

Now with HTTP_PROVIDERS deprecated and removed, how do I provide it?

Thanks!

回答1:

@NgModule({
  imports: [HttpModule],
  ...
})
class AppModule {}

or copy the definition of HTTP_PROVIDERS from the Angular2 source to your source and use it there like before.

const HTTP_PROVIDERS = [
    {provide: Http, useFactory: 
      (xhrBackend: XHRBackend, requestOptions: RequestOptions): Http =>
          new Http(xhrBackend, requestOptions), 
          deps: [XHRBackend, RequestOptions]},
    BrowserXhr,
    {provide: RequestOptions, useClass: BaseRequestOptions},
    {provide: ResponseOptions, useClass: BaseResponseOptions},
    XHRBackend,
    {provide: XSRFStrategy, useFactory: () => new CookieXSRFStrategy()},
];

You can also create an injector yourself using these providers like

let resolvedProviders = ReflectiveInjector.resolve(HTTP_PROVIDERS);
let injector = ReflectiveInjector.fromResolvedProviders(resolvedProviders, /* this.injector (parent injector if any) */ );
var http = child.get(Http);

See also Inject Http manually in angular 2