从Plain Ol'的TypeScript类访问@ angular/http Http客户端 [英] Access @angular/http Http Client from Plain Ol' TypeScript Class

查看:52
本文介绍了从Plain Ol'的TypeScript类访问@ angular/http Http客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 User 类,它没有任何NG2元数据等.但是我想让它从"@ angular/访问 Http http" .将此类引入NG DI提供程序/注入器系统以便我可以访问 Http 的最佳方法是什么?

我要的东西如下:

 从"@ angular/http"导入{Http,Response}导出类用户{构造函数(私有_email:string){}公共reload(){this.http.get("http://www.example.com").订阅(...)}} 

解决方案

我认为这不是一个好主意,但是无论如何,请参见下面的方法:

Http 具有相当大的依赖性,因此我认为最简单的方法是使用 constructor(){让注入器= ReflectiveInjector.resolveAndCreate([{提供:Http,useFactory:httpFactory,deps:[XHRBackend,RequestOptions]},BrowserXhr,{提供:RequestOptions,useClass:BaseRequestOptions},{提供:ResponseOptions,useClass:BaseResponseOptions},XHRBackend,{提供:XSRFStrategy,useFactory:_createDefaultCookieXSRFStrategy},]);this.http = jector.get(Http);}

I have a class User that does not have any NG2 metadata, etc.. But I would like to have it access Http from "@angular/http". What is the best way to bring this class into the NG DI provider/injector system so that I can access Http?

I'm going for something like the following:

import {Http, Response} from "@angular/http"

export class User {
  constructor(private _email:string){}

  public reload(){
    this.http.get("http://www.example.com")
      .subscribe(...)
  }
}

解决方案

I don't think this is a good idea, but anyhow, see below an approach how it could be done:

Http has quite some dependencies, therefore the easiest way in my opinion is to create an injector with the providers specified in the HttpModule and then let the injector create an instance:

constructor() {   
  let injector = ReflectiveInjector.resolveAndCreate([
    {provide: Http, useFactory: httpFactory, deps: [XHRBackend, RequestOptions]},
    BrowserXhr,
    {provide: RequestOptions, useClass: BaseRequestOptions},
    {provide: ResponseOptions, useClass: BaseResponseOptions},
    XHRBackend,
    {provide: XSRFStrategy, useFactory: _createDefaultCookieXSRFStrategy},
  ]);
  this.http = injector.get(Http);
}

这篇关于从Plain Ol'的TypeScript类访问@ angular/http Http客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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