Angular 2 - 手动实例化 (Http) 服务
Angular 2 - Instantiate (Http) Service Manually
是否可以手动实例化 Http 服务而无需将其作为构造函数参数?
export class SimpleGridServer {
private http: Http;
constructor(public options: SimpleServerData) {
http = new Http(.../* Argument here */);
}
}
实例化这个class。
var grid = new SimpleGridServer({/* options */});
我想实例化此 class,而不依赖于导入 SimpleGridServer
的 component
的 Http 服务。
如果这是可能的,这种情况的缺点是什么?
If this is possible, what is the drawback for this scenario?
您需要处于 Angular DI 工作流程中才能使用 Angular 内容。
您可以直接获取 angular 的注入器的句柄:
import {ReflectiveInjector} from '@angular/core';
import {HTTP_PROVIDERS, Http, Headers} from "@angular/http";
const injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
const http = injector.get(Http);
是否可以手动实例化 Http 服务而无需将其作为构造函数参数?
export class SimpleGridServer {
private http: Http;
constructor(public options: SimpleServerData) {
http = new Http(.../* Argument here */);
}
}
实例化这个class。
var grid = new SimpleGridServer({/* options */});
我想实例化此 class,而不依赖于导入 SimpleGridServer
的 component
的 Http 服务。
如果这是可能的,这种情况的缺点是什么?
If this is possible, what is the drawback for this scenario?
您需要处于 Angular DI 工作流程中才能使用 Angular 内容。
您可以直接获取 angular 的注入器的句柄:
import {ReflectiveInjector} from '@angular/core';
import {HTTP_PROVIDERS, Http, Headers} from "@angular/http";
const injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
const http = injector.get(Http);