Angular2 / http异常没有ConnectionBackend

时间:2016-02-23 19:51:30

标签: http service angular

我尝试使用angular2 http请求,但是我收到以下错误: [错误]例外:没有ConnectionBackend的提供者! (AppComponent - > Http - > ConnectionBackend)

我已经设置了一个具有相同问题的准系统应用程序,并且不知道导致它的原因。

提前致谢

app.component.ts

import {Component} from 'angular2/core';
import {Http, Headers} from 'angular2/http';

@Component({
  selector: 'app',
  template: `
    <button (click)="getEmployee()">Get</button>
    <p>{{employee.email}}</p>

  `,
  providers: [Http]
})

export class AppComponent {
  employee: {"email": "bob"};
  http: Http;

  constructor(http:Http){
    this.http = http;
  }

  getEmployee(){
    this.http.get('localhost:8080/employee-rates?id=0')
      .map(response => response.json()).subscribe(result => this.employee = result);
  }


}

main.ts

import {AppComponent} from './app.component';
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS, HTTP_BINDINGS} from 'angular2/http';

bootstrap(AppComponent, [
  HTTP_PROVIDERS, HTTP_BINDINGS
]);

的index.html

<html>

  <head>
    <base href="/">
    <title>Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="js/es6-shim/es6-shim.min.js"></script>
    <script src="js/systemjs/dist/system-polyfills.js"></script>

    <script src="js/angular2/bundles/angular2-polyfills.js"></script>
    <script src="js/systemjs/dist/system.src.js"></script>
    <script src="js/rxjs/bundles/Rx.js"></script>
    <script src="js/angular2/bundles/angular2.dev.js"></script>
    <script src="js/angular2/bundles/http.dev.js"></script>

    <!-- 2. Configure SystemJS -->
    <script>
      System.config({
        packages: {
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>

  </head>

  <!-- 3. Display the application -->
  <body>
    <div class='small-12'>
      <app>Loading...</app>
    </div>
  </body>

</html>

3 个答案:

答案 0 :(得分:20)

From Angular 2 RC5 version, in your NgModule file, add:

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

@NgModule({
    imports:      [
        ...
        HttpModule ]

答案 1 :(得分:11)

从代码中删除HTTP_BINDINGS。它们已被弃用并引用HTTP_PROVIDERS,因此您就像使用提供商两次一样。

bootstrap(AppComponent, [HTTP_PROVIDERS]);

此外,您在组件中不需要providers: [Http],因为您在引导程序中注入了HTTP_PROVIDERS。将其添加到组件的提供者将创建该服务的新实例。

@Component({
  providers: []
})

答案 2 :(得分:2)

的src / main.ts

import { HTTP_PROVIDERS, ConnectionBackend } from '@angular/http';

bootstrap(AppComponent, [
  HTTP_PROVIDERS,
  ConnectionBackend
]);

使用 angular-cli@1.0.0-beta.10 angular@2.0.0-rc.4