获取此信息"没有ConnectionBackend的提供商!"尝试将http
与promise一起使用时出错。
// ... tl;dr import a bunch of stuff
platformBrowserDynamic().bootstrapModule(MyModule);
// ... tl;dr import a bunch of stuff
@NgModule({
declarations: [
PostComponent
],
providers: [
Actions,
MyService,
Http
],
imports: [
...
],
bootstrap: [MyComponent]
})
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {MyService} from './../services/myService'
import {Post} from './post';
@Component({
templateUrl: 'post.component.html',
styleUrls: ['post.component.css']
})
export class MyComponent implements OnInit {
post: Observable<Post>;
postId : Number;
constructor(private route: ActivatedRoute, private router: Router, private service:MyService) {
}
ngOnInit() {
this.route.params.subscribe(params => {
this.postId = +params['id'];
this.post = this.service.getPostById(this.postId);
});
}
}
import {Injectable} from "@angular/core"
import {Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Post} from './../post/post';
import 'rxjs/Rx'
@Injectable()
export class MyService {
endpoint_url:String = "http://someurl.com/";
constructor(private http: Http){
}
getPostById (id:Number) : Observable<Post> {
return this.http.get(this.endpoint_url + id.toString()).map(res => res.json());
}
}
一切看起来不错,但后来我收到了这个错误:
error_handler.js:51Error: Uncaught (in promise): Error: Error in ./MyComponent class MyComponent_Host - inline template:0:0 caused by: No provider for ConnectionBackend!
at resolvePromise (zone.js:429)
at zone.js:406
...
here is the docs for ConnectionBackend。我想我只需要在providers
中向myModule
添加内容?
答案 0 :(得分:93)
在您的模块中导入HttpModule,而不是将Http
注册为提供者。
import {HttpModule} from '@angular/http';
@NgModule({
imports: [HttpModule],
declarations: [
PostComponent
],
providers: [
Actions,
MyService
],
bootstrap: [MyComponent]
})
HttpModule为其所有服务注册提供者。