我得到的例外:没有提供Http!我做错了什么?

import {Http, Headers} from 'angular2/http';
import {Injectable} from 'angular2/core'


@Component({
    selector: 'greetings-ac-app2',
    providers: [],
    templateUrl: 'app/greetings-ac2.html',
    directives: [NgFor, NgModel, NgIf, FORM_DIRECTIVES],
    pipes: []
})
export class GreetingsAcApp2 {
    private str:any;

    constructor(http: Http) {

        this.str = {str:'test'};

        http.post('http://localhost:18937/account/registeruiduser/',
            JSON.stringify(this.str),
            {
                headers: new Headers({
                    'Content-Type': 'application/json'
                })
            });

当前回答

**

简单的方法:在app.module.ts中导入HttpModule和HttpClientModule

**

import { HttpClientModule } from '@angular/common/http';
import { HttpModule } from '@angular/http';



@NgModule({
 declarations: [
   AppComponent, videoComponent, tagDirective, 
 ],
 imports: [
  BrowserModule, routing, HttpClientModule, HttpModule

],
providers: [ApiServices],
bootstrap: [AppComponent]
})
export class AppModule { }

其他回答

我在代码中遇到过这个问题。我只把这个代码放在我的app.module.ts中。

import { HttpModule } from '@angular/http';

@NgModule({
  imports:      [ BrowserModule, HttpModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

只需包含以下库:

import { HttpModule } from '@angular/http';
import { YourHttpTestService } from '../services/httpTestService';

并在providers部分中包含HTTP类,如下所示:

@Component({
  selector: '...',
  templateUrl: './test.html',
  providers: [YourHttpTestService]
**

简单的方法:在app.module.ts中导入HttpModule和HttpClientModule

**

import { HttpClientModule } from '@angular/common/http';
import { HttpModule } from '@angular/http';



@NgModule({
 declarations: [
   AppComponent, videoComponent, tagDirective, 
 ],
 imports: [
  BrowserModule, routing, HttpClientModule, HttpModule

],
providers: [ApiServices],
bootstrap: [AppComponent]
})
export class AppModule { }

在app.module.ts文件中导入HttpModule。

import { HttpModule } from '@angular/http';
import { YourHttpTestService } from '../services/httpTestService';

还记得在import下面声明HttpModule,如下所示:

imports: [
    BrowserModule,
    HttpModule
  ],

>= Angular 4.3

用于引入的HttpClientModule

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule, // if used
    HttpClientModule,
    JsonpModule // if used
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Angular2 >= RC.5

将HttpModule导入到你使用它的模块中(例如AppModule):

import { HttpModule } from '@angular/http';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule, // if used
    HttpModule,
    JsonpModule // if used
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

导入HttpModule非常类似于在以前的版本中添加HTTP_PROVIDERS。