我得到的例外:没有提供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'
})
});
导入HttpModule
import { HttpModule } from '@angular/http';
@NgModule({
imports: [ BrowserModule, HttpModule ],
providers: [],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export default class AppModule { }
platformBrowserDynamic().bootstrapModule(AppModule);
理想情况下,您可以将这些代码拆分到两个单独的文件中。
欲了解更多信息,请阅读:
https://v2.angular.io/docs/ts/latest/cookbook/rc4-to-rc5.html
https://v2.angular.io/docs/ts/latest/guide/ngmodule.html
如果在测试中出现此错误,则应该为所有服务创建假服务:
例如:
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
}));
在2016年9月14日发布的Angular 2.0.0版本中,你仍然在使用HttpModule。你的主app.module.ts看起来是这样的:
import { HttpModule } from '@angular/http';
@NgModule({
bootstrap: [ AppComponent ],
declarations: [ AppComponent ],
imports: [
BrowserModule,
HttpModule,
// ...more modules...
],
providers: [
// ...providers...
]
})
export class AppModule {}
然后在你的app.ts中,你可以这样引导:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/main/app.module';
platformBrowserDynamic().bootstrapModule(AppModule);