Angular 2.0.0-rc.1 + 业力 : provide RouteSegment

标签 angular angular2-routing

当组件注入(inject) RouteSegment 时,仅在测试中提供 RouteSegment 是不够的:

组件.ts:

export class ComponentToTest {
  private param: string;

  constructor(routeSegment: RouteSegment) {
    this.param = routeSegment.getParam('param');
    this.getData();
  }
}

组件.spec.ts:

import {Router, RouteSegment} from '@angular/router';

import {it, inject, beforeEachProviders} from '@angular/core/testing';
import {ROUTER_FAKE_PROVIDERS} from '@angular/router/testing';

import {ComponentToTest} from './component';

describe('ComponentToTest', () => {
  beforeEachProviders(() => [
    ROUTER_FAKE_PROVIDERS,
    RouteSegment,
    ComponentToTest
  ]);

  it('should call getData() on contruct', inject([Router], (router) => {
    spyOn(ComponentToTest.prototype, 'getData');
    expect(ComponentToTest.prototype.getData).not.toHaveBeenCalled();
    let component = new ComponentToTest(router);
    expect(ComponentToTest.prototype.getData).toHaveBeenCalled();
  }));
});

会出现以下错误:

Error: Cannot resolve all parameters for 'RouteSegment'(?, ?, ?, ?, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'RouteSegment' is decorated with Injectable.

我不知道如何提供 RouteSegment 参数。

最佳答案

我有同样的问题,我不得不查看 Angular 路由器代码和它们在 repo 中的规范。您应该能够像这样提供 routeSegment:

import {RouteSegment, Router} from '@angular/router';
provide(RouteSegment, {useFactory: (r: any) => r.routeTree.root, deps: [Router]})

或者您可以模拟一个新的 RouteSegment,类似于您对 RouteParams 所做的:

provide(RouteParams, { useValue: new RouteParams({ page: 'terms-conditions' }) }),

现在是这样的:

provide(RouteSegment, { useValue: new RouteSegment([], { page: 'terms-conditions' }, null, null, null) }),

要创建它,您只需向它传递几个额外的参数。

关于 Angular 2.0.0-rc.1 + 业力 : provide RouteSegment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37147812/

相关文章:

json - 如何在嵌套的 json 对象上执行 ngFor 循环?

html - 当侧边栏折叠为图标时,导航栏文本会溢出

Angular2 - 使用服务的组件之间的交互

javascript - 找不到要加载的主 socket 'XYZComponent'

angular - ViewChildren 传递多个组件

node.js - 无法从 ionic-native 安装 ‘File’ - 依赖项相关?

typescript - Angular 2 : How to Prevent my data and html view by not reloading component on browser back navigation

Angular 2 : Loading modules dynamically from a given folder

javascript - Angular 2 - 后备路线不起作用

Angular 测试 HTTP Post 调用