这是我的app.component.html文件
这是我的app.component.ts文件
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Headers, Http, Response } from '@angular/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
submitted = false;
userName = '';
ngOnInit() {
}
constructor(private http: Http;) { }
private generateOtp(){
this.http.get('http://localhost:8080/generateotp/'+this.userName)
.subscribe(
(res:Response)=> {
const otpCheck = res.json();
console.log(otpCheck);
}
)
}
generateOtpSubmit() {
this.submitted = true;
this.generateOtp();
}
}
这是我的app.module.ts文件
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { Http } from '@angular/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [Http],
bootstrap: [AppComponent]
})
export class AppModule { }
每当我尝试初始化app.component.ts文件中存在的constructor(private http: Http;) { }
中的任何变量时,我在浏览器控制台中收到此错误并且页面未加载。
Error: StaticInjectorError(AppModule)[Http -> ConnectionBackend]:
StaticInjectorError(Platform: core)[Http -> ConnectionBackend]:
NullInjectorError: No provider for ConnectionBackend!
内部错误图片:
答案 0 :(得分:3)
在较新的Angular版本(从4.3开始)中,您需要导入HttpClientModule
并将其添加到导入中,您无需单独提供任何内容。另请注意,它位于@angular/common/http
。您需要用于请求的类称为HttpClient
。使用它而不是Http
。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
但是,如果您仍想使用我未提供的Http
,则需要从HttpModule
导入@angular/http
并将其添加到导入中。您仍然无需在提供商中单独添加任何内容。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
bootstrap: [AppComponent]
})
export class AppModule { }