Angular 2 : No provider for ConnectionBackend

标签 angular angular-http

得到这个“ConnectionBackend 没有提供者!”尝试使用带有 promise 的 http 时出错。

主.ts

// ... tl;dr import a bunch of stuff

platformBrowserDynamic().bootstrapModule(MyModule);

我的模块.ts

// ... tl;dr import a bunch of stuff

@NgModule({
 declarations: [
        PostComponent
  ],
  providers: [
    Actions,
    MyService,
    Http
  ],
  imports: [
    ...
  ],
  bootstrap: [MyComponent]
})

我的组件.ts

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);
    });
  }

}

我的服务.ts

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 .我想我只需要向 myModule 中的 providers 添加一些内容?

最佳答案

在您的模块中导入 HttpModule 而不是将 Http 注册为提供者。

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

@NgModule({
 imports: [HttpModule], 
 declarations: [
        PostComponent
  ],
  providers: [
    Actions,
    MyService

  ],
  bootstrap: [MyComponent]
})

HttpModule 为其所有服务注册提供者。

关于 Angular 2 : No provider for ConnectionBackend,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40098413/

相关文章:

angular - Typescript 中反序列化对象的 Getter 方法

angular - 错误: Cannot find a differ supporting object '[object Object]' of type 'object' . NgFor只支持绑定(bind)到Iterables比如Arrays

带有 Auth0 路由错误 404 的 Angular 2

angular - ng 服务无法编译

angular - 如何在剑道组合框中添加工具提示?

angularjs - 始终在 $http 之前和之后执行操作

javascript - Http 服务工厂在 Angular 中将未定义返回给 Controller

angularjs - 如何在 angularjs 中设置条件 $resource 超时?

angular - Ionic 3 使用语法错误,但无法使用此错误构建

angular - 在路由中传递对象