错误:未捕获(承诺):错误:StaticInjectorError(AppModule)[Http]:StaticInjectorError Http

时间:2019-06-29 13:55:59

标签: angular

收到此错误

ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[Http]: 
  StaticInjectorError(Platform: core)[Http]: 
    NullInjectorError: No provider for Http!
Error: StaticInjectorError(AppModule)[Http]: 

这里是代码 服务:

import { Injectable } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { HttpModule } from '@angular/http';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class MakeService {

  constructor(private http: Http) { }

  getMakes() {
    return this.http.get('api/makes')
      .pipe(map((response) => response.json()));
  }
}

应用模块

import { MakeService } from './services/make.service';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { HomeComponent } from './home/home.component';
import { CounterComponent } from './counter/counter.component';
import { FetchDataComponent } from './fetch-data/fetch-data.component';
import { VehicleFormComponent } from './vehicle-form/vehicle-form.component';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    CounterComponent,
    FetchDataComponent,
    VehicleFormComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    RouterModule.forRoot([
      { path: '', component: HomeComponent, pathMatch: 'full' },
      { path: 'vehicles/new', component: VehicleFormComponent },
      { path: 'counter', component: CounterComponent },
      { path: 'fetch-data', component: FetchDataComponent },
    ])
  ],
  providers: [
    MakeService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

1 个答案:

答案 0 :(得分:1)

您似乎在Angular 4.3之前和Angular 4.3之后混合了用于进行Http调用的语法

Angular 4.3和以前的版本曾经使用Http,为此,需要添加HttpModule

您最有可能使用的是Angular,版本大于4.3,RxJS版本大于5.5

您应该使用HttpClient。您只需要这个:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class MakeService {

  constructor(private http: HttpClient) { }

  getMakes() {
    return this.http.get('api/makes');
  }
}