本文介绍了Angular 2:没有ConnectionBackend的提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取此没有ConnectionBackend的提供程序!"尝试使用带有承诺的http时出错.

Get this "No provider for ConnectionBackend!" error when trying to use http with a promise.

// ... 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());
    }
}

一切看起来不错,但是我得到了这个错误:

All looks good but then I get this error:

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
...

这是ConnectionBackend的文档.我想我只需要在myModule中的providers中添加一些内容?

And here is the docs for ConnectionBackend. I think I just need to add something to providers in myModule?

推荐答案

将HttpModule导入模块中,而不是将Http注册为提供者.

Import the HttpModule in your module instead of registering Http as a provider.

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

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

  ],
  bootstrap: [MyComponent]
})

HttpModule为其所有服务注册提供程序.

The HttpModule registers providers for all its services.

这篇关于Angular 2:没有ConnectionBackend的提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 02:49