在Angular 4中手动注入Http [英] Inject Http manually in Angular 4

查看:51
本文介绍了在Angular 4中手动注入Http的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to manually bootstrap an Angular 4 app (created with CLI). In main.ts I am doing this:

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);
});

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

I seem to get a valid Http instance but when I use it (http.get) I get this error:

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

我的http对象看起来像这样:

My http object looks like this:

推荐答案

您可以在Angular像这样开始使用ReflectiveInjector之前使用HttpClient服务:

You can use HttpClient service before the Angular starts using ReflectiveInjector like this:

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);
});

此行:

getAnnotations(HttpClientModule).providers

引用在HttpClientModule上注册的所有提供程序,因此您不必手动指定它们. 此答案详细说明了getAnnotations功能.

references all providers that are registered on the HttpClientModule so you don't have to specify them manually. This answer explains the getAnnotations function in great details.

我展示的方法类似于将HttpClientModule导入到AppModule时所执行的操作:

The approach I've shown is "sort of" the similar to what you're doing when importing HttpClientModule into the AppModule:

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

有关详细信息,请参见此朋克车.

See this plunker for details.

这篇关于在Angular 4中手动注入Http的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆