Angular 2:错误:没有Http的提供者! (AccountService - > Http)

时间:2016-06-13 16:39:50

标签: angular

我的main.ts文件如下所示:

import { bootstrap } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { HTTP_PROVIDERS } from '@angular/http'
import { ClientDashboardTwoAppComponent, environment } from './app/';

if (environment.production) {
  enableProdMode();
}

bootstrap(ClientDashboardTwoAppComponent, [HTTP_PROVIDERS]);

我尝试将http服务添加到我的服务中,因为我现在只是硬编码all()的响应:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http'

@Injectable()
export class AccountService {
  constructor(private http: Http) {} // <------------------ just added and it broke my tests

  all() {
    return Promise.resolve([
      { name: "Account 1" },
      { name: "Account 2" },
      { name: "Account 3" },
    ]);
  }

}

然而,该行使用此服务打破了组件的测试(这些规格来自角度cli生成器,我所做的只是在AccountService中添加beforeEachProviders()提供程序):

import {
  beforeEach,
  beforeEachProviders,
  describe,
  expect,
  it,
  inject,
} from '@angular/core/testing';
import { ComponentFixture, TestComponentBuilder } from '@angular/compiler/testing';
import { Component } from '@angular/core';
import { By } from '@angular/platform-browser';
import { EngagementTableComponent } from './engagement-table.component';
import { AccountService } from '../account.service';

describe('Component: EngagementTable', () => {
  let builder: TestComponentBuilder;

  beforeEachProviders(() => [EngagementTableComponent, AccountService]);
  beforeEach(inject([TestComponentBuilder], function (tcb: TestComponentBuilder) {
    builder = tcb;
  }));

  it('should inject the component', inject([EngagementTableComponent],
      (component: EngagementTableComponent) => {
    expect(component).toBeTruthy();
  }));

  it('should create the component', inject([], () => {
    return builder.createAsync(EngagementTableComponentTestController)
      .then((fixture: ComponentFixture<any>) => {
        let query = fixture.debugElement.query(By.directive(EngagementTableComponent));
        expect(query).toBeTruthy();
        expect(query.componentInstance).toBeTruthy();
      });
  }));
});

@Component({
  selector: 'test',
  template: `
    <engagement-table></engagement-table>
  `,
  directives: [EngagementTableComponent]
})
class EngagementTableComponentTestController {
}

我错过了一步吗?我是否必须在规格中注入一些东西?

1 个答案:

答案 0 :(得分:1)

确保添加package.json@angular/http包以正确加载Http依赖模块。

"dependencies": {
    ....,
    "@angular/http": "2.0.0-rc.1", //<--add it in package.json
    ....,
    ....
}