错误:没有Http的提供程序! (MyService-> Http) [英] Error: No provider for Http! (MyService -> Http)
问题描述
我正在使用角度2.
@Injectable()
export class MyService {
constructor(private http: Http, @Inject('name') @Optional() public name?: string) {
}
在appModule内部,我正在尝试使用提供程序提供服务
inside appModule I'm trying to use provider for my service
import { Http } from '@angular/http/';
@NgModule({
bootstrap: [App],
declarations: [
App
],
imports: [ // import Angular's modules
BrowserModule,
HttpModule
],
providers: [
Http, // if I comment this out I'm getting ERROR Error: No provider for
// Http! (MyService -> Http)
MyService,
[
{ provide: 'name', useValue: '' }
],
....,
在AppComponent内部,我正在使用反射式注入器
Inside AppComponent I'm using Reflective injector
const injector = ReflectiveInjector.resolveAndCreate(
[MyService,
{
provide: 'name', useValue: 'my name'
}
]);
但是我越来越 情况一: 内部提供商,如果我有关注
But I'm getting case one: Inside providers if I have following
providers: [ Http ]
那我就得到
未处理的承诺拒绝:没有ConnectionBackend的提供者! ; 区域:;任务:Promise.then;值:错误:没有提供者 ConnectionBackend!
Unhandled Promise rejection: No provider for ConnectionBackend! ; Zone: ; Task: Promise.then ; Value: Error: No provider for ConnectionBackend!
如果不使用Http,providers: [ ]
我会得到
and if left Http out, providers: [ ]
I'm getting
错误:没有Http的提供程序! (MyService-> Http)
Error: No provider for Http! (MyService -> Http)
在实际服务中,我有类似的构造函数
On actual service I'm having constructor like
@Injectable()
export class MyService {
constructor(private http: Http, @Inject('name') @Optional() public name?: string) {
}
更新: 在我正在注入的AppComponent中 构造函数(private parentInjector:Injector){ }
Update: inside AppComponent I'm injecting constructor(private parentInjector:Injector){ }
const injector = ReflectiveInjector.resolveAndCreate(
[MyService,
{
provide: 'name', 'abc'
}
], this.parentInjector);
this.security = injector.get(MyService);
未处理的承诺拒绝:没有ConnectionBackend的提供者! ; 区域:;任务:Promise.then;值:错误:没有提供者 ConnectionBackend!
Unhandled Promise rejection: No provider for ConnectionBackend! ; Zone: ; Task: Promise.then ; Value: Error: No provider for ConnectionBackend!
推荐答案
您需要传递父注入器(来自Angular应用程序),否则创建的注入器将只知道您显式传递的提供者
You need to pass the parent injector (from the Angular application), otherwise the created injector will only know the providers you pass explicitely
constructor(private parentInjector:Injector) {
}
...
const injector = ReflectiveInjector.resolveAndCreate(
[MyService,
{
provide: 'name', useValue: 'my name'
}
], this.parentInjector);
另请参见 https://angular.io/api/core/ReflectiveInjector#resolveAndCreate
这篇关于错误:没有Http的提供程序! (MyService-> Http)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!