在Angular 4中手动注入Http

hho*_*tij 2 angular

我想手动引导Angular 4应用程序(使用CLI创建).在main.ts我这样做:

const injector = ReflectiveInjector.resolveAndCreate([
  Http,
  BrowserXhr,
  {provide: RequestOptions, useClass: BaseRequestOptions},
  {provide: ResponseOptions, useClass: BaseResponseOptions},
  {provide: ConnectionBackend, useClass: XHRBackend},
  {provide: XSRFStrategy, useFactory: () => new CookieXSRFStrategy()},
]);
const http = injector.get(Http);

http.get('assets/configs/configuration.json')
  .map((res: Response) => {
    return res.json();
  }).subscribe((config: Configuration) => {
  configuration = config;
  console.log(JSON.stringify(configuration));
  platformBrowserDynamic().bootstrapModule(AppModule);
});
Run Code Online (Sandbox Code Playgroud)

我似乎得到一个有效的Http实例,但当我使用它(http.get)时,我收到此错误:

Uncaught TypeError: Cannot read property 'getCookie' of null
    at CookieXSRFStrategy.webpackJsonp.../../../http/@angular/http.es5.js.CookieXSRFStrategy.configureRequest (vendor.bundle.js:141626)
Run Code Online (Sandbox Code Playgroud)

我的http对象如下所示: 在此输入图像描述

Kun*_*vič 5

作为另一种方法,您可以使用本机浏览器fetch api。所以你不必处理 Angular http 等

我就是这样做的:

fetch(configUrl, { method: 'get' })
.then((response) => {
  response.json()
    .then((data: any) => {
      if (environment.production) {
        enableProdMode();
      };
      platformBrowserDynamic([{ provide: AppSettings, useValue: new AppSettings(data.config) }]).bootstrapModule(AppModule);
    });
});
Run Code Online (Sandbox Code Playgroud)

但请记住,fetch在旧浏览器中并没有得到太多的喜爱,所以如果你想支持旧浏览器,你需要像这样使用Whatwg-fetch来进行 polyfil 。npm install whatwg-fetch --saveimport 'whatwg-fetch'polyfills.ts

更新: 是的,您可以使用XMLHttpRequest但您将获得相同的浏览器支持,因为fetch只是XMLHttpRequest的现代替代品。


Max*_*kyi 5

您可以HttpClient在Angular开始使用之前使用服务,ReflectiveInjector如下所示:

import { ReflectiveInjector } from '@angular/core';
import { HttpClient, HttpClientModule } from '@angular/common/http';
const injector = ReflectiveInjector.resolveAndCreate(getAnnotations(HttpClientModule)[0].providers);

const http = injector.get(HttpClient);
http.get('/posts/1').subscribe((r) => {
  ConfigurationService.configuration = <Configuration>JSON.parse(config);
  platformBrowserDynamic().bootstrapModule(AppModule);
});
Run Code Online (Sandbox Code Playgroud)

这一行:

getAnnotations(HttpClientModule).providers
Run Code Online (Sandbox Code Playgroud)

引用所有已注册的提供程序,HttpClientModule因此您无需手动指定它们.这个答案getAnnotations非常详细地解释了这个功能.

我所展示的方法是"类似",类似于您在导入时所执行HttpClientModule的操作AppModule:

@NgModule({
    imports: [HttpClientModule, ...],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此plunker.