Angular2调用Web API报错No provider for Http,求解决方案
Fixing "No provider for Http" Error in Angular 2
Looks like you've hit a super common Angular 2 gotcha! The issue here is that even though you're injecting Http into your service class, Angular doesn't provide this service by default—you need to explicitly import the module that registers all the necessary providers for it.
Here's how to fix it step by step:
- Open your
Module.tsfile and add the import forHttpModulefrom@angular/http:
import { HttpModule } from '@angular/http';
- Add
HttpModuleto theimportsarray in your@NgModuledecorator. This tells Angular to set up all the dependencies needed for the HTTP service to work:
@NgModule({ imports: [BrowserModule, ReactiveFormsModule, appRouterModule, HttpModule], // Add HttpModule here declarations: [AppComponent, LoginComponent, RegistrationComponent], bootstrap: [AppComponent], providers: [services] }) export class AppModule { }
Quick extra tips:
- If you're working with Angular 4.3 or later, the official recommendation is to use the newer
HttpClientModule(from@angular/common/http) instead of the oldHttpModule. It comes with nicer features like automatic JSON parsing and better type support—worth checking out if your project version allows it! - A small style note: TypeScript class names usually start with a capital letter, so renaming
servicestoServiceswould make your code more consistent with standard conventions.
Once you make these changes, restart your Angular app and the "No provider for Http" error should disappear entirely. Your login API call should now execute without issues!
内容的提问来源于stack exchange,提问作者Hardik Gondalia
相关产品推荐
相关产品推荐

