ts文件Angular 4中构造函数中的变量初始化错误

时间:2018-01-23 05:13:15

标签: angular typescript

这是我的app.component.html文件

                 

PL Auth

                  用户名:            

      密码:              

      生成OTP            

      输入OTP:              

      登录           

这是我的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!

内部错误图片:

Internal error in browser console

1 个答案:

答案 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 { }