Javascript 如何在运行时确定可注入的角度服务?
我为没有为这段代码创建plunker提前表示歉意,它需要许多第三方控件才能运行 我的问题是关于在运行时根据一些条件选择服务、依赖项注入 对于这个例子,我们只讨论一个服务Javascript 如何在运行时确定可注入的角度服务?,javascript,angular,Javascript,Angular,我为没有为这段代码创建plunker提前表示歉意,它需要许多第三方控件才能运行 我的问题是关于在运行时根据一些条件选择服务、依赖项注入 对于这个例子,我们只讨论一个服务 import { Injectable } from '@angular/core'; import { Http, Response} from '@angular/http'; @Injectable() export class Service1 { constructor ( private h
import { Injectable } from '@angular/core';
import { Http, Response} from '@angular/http';
@Injectable()
export class Service1 {
constructor (
private http: Http) {
}
}
在我的组件中,如果我有一个固定的组件,那么一切都很好
import {Component, ViewChild, OnChanges, Input, ReflectiveInjector, SimpleChange} from '@angular/core';
import {Observable} from 'rxjs/Rx';
import { Service1 } from './my.service.1';
@Component({
providers: [
Service1
],
moduleId: module.id,
selector: 'my-component',
templateUrl: './my-component.component.html'
})
export class MyComponent {
constructor(private service : Service1
) {
}
在上述情况下,一切正常,没有运行时错误
现在,如果我更改为动态版本,我会得到一个错误
异常:中出现错误,原因是:没有Http提供程序!(Service1->Http)
导致错误的代码版本为:
我为MyComponent添加了一个成员变量:private service:any=''
构造函数现在看起来像
constructor() {
// this does not work with the http module
let injector = ReflectiveInjector.resolveAndCreate([Service1]);
this.service = injector.get(Service1);
}
有人看到了导致上述错误的原因吗?不要忘记将Http添加到传入的数组
ReflectiveInjector.resolveAndCreate
:
let injector = ReflectiveInjector.resolveAndCreate([Service1,Http]);
不要忘记将Http添加到传入的数组
ReflectiveInjector.resolveAndCreate
:
let injector = ReflectiveInjector.resolveAndCreate([Service1,Http]);
添加您的建议后没有任何更改。抱歉,我只是查找您,这很困难,因为Http有自己的依赖项,而这些依赖项也有自己的依赖项,因此您必须向
ReflectVenjector
提供所有这些依赖项,才能获得服务1
。请看这里,添加您的推荐后没有任何更改。对不起,我只是找您,这很困难,因为Http有自己的依赖项,这些依赖项也有自己的依赖项,因此您必须向ReflectiveInjector
提供所有这些依赖项才能获得服务1
。看看这里