我得到的例外:没有提供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'
                })
            });

当前回答

因为钢筋混凝土。5 .你得做点什么

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

platformBrowserDynamic().bootstrapModule(AppModule);

其他回答

如果在测试中出现此错误,则应该为所有服务创建假服务:

例如:

import { YourService1 } from '@services/your1.service';
import { YourService2 } from '@services/your2.service';

class FakeYour1Service {
 public getSomeData():any { return null; }
}

class FakeYour2Service {
  public getSomeData():any { return null; }
}

在beforeEach中:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    providers: [
      Your1Service,
      Your2Service,
      { provide: Your1Service, useClass: FakeYour1Service },
      { provide: Your2Service, useClass: FakeYour2Service }
    ]
  }).compileComponents();  // compile template and css
}));

我只是在我的app.module.ts中添加了这两个:

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

&

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

现在它的工作很好.... 别忘了加上

导入:[]数组

从@angular/http导入{HttpModule};打包到模块中。Ts文件并将其添加到导入中。

因为钢筋混凝土。5 .你得做点什么

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

platformBrowserDynamic().bootstrapModule(AppModule);

在使用它之前,将HttpModule添加到app.module.ts文件中的imports数组中。

从@angular/http导入{HttpModule}; @NgModule ({ 声明:[ AppComponent, CarsComponent ], 进口:[ BrowserModule, step 4 ], 供应商:[], 引导(AppComponent): }) 导出类AppModule {}