Error: No provider for Http! (MyService -> Http)

2020-02-15 15:52发布

问题:

I'm using angular 2.

@Injectable()
export class MyService {
    constructor(private http: Http, @Inject('name') @Optional() public name?: string) {            
}

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: ''  }      
    ],
....,

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 ]

then I'm getting

Unhandled Promise rejection: No provider for ConnectionBackend! ; Zone: ; Task: Promise.then ; Value: Error: No provider for ConnectionBackend!

and if left Http out, providers: [ ] I'm getting

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) {

    }

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

Unhandled Promise rejection: No provider for ConnectionBackend! ; Zone: ; Task: Promise.then ; Value: Error: No provider for ConnectionBackend!

回答1:

Use this module for latest version of Angular:

import { HttpClient, HttpHeaders } from '@angular/common/http';



回答2:

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

See also https://angular.io/api/core/ReflectiveInjector#resolveAndCreate