【问题标题】:Angular 2 : No provider for ConnectionBackendAngular 2:没有 ConnectionBackend 的提供者
【发布时间】:2016-10-18 02:06:30
【问题描述】:

获取此“无 ConnectionBackend 提供程序!”尝试使用带有承诺的http 时出错。

main.ts

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

platformBrowserDynamic().bootstrapModule(MyModule);

myModule.ts

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

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

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

}

myService.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 添加一些内容?

【问题讨论】:

    标签: angular angular-http


    【解决方案1】:

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

    import {HttpModule} from '@angular/http';
    
    @NgModule({
     imports: [HttpModule], 
     declarations: [
            PostComponent
      ],
      providers: [
        Actions,
        MyService
    
      ],
      bootstrap: [MyComponent]
    })
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 2015-07-26
      • 2018-01-09
      相关资源
      最近更新 更多