本文介绍了Angular2 RC5 模拟激活路由参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够模拟激活的路由参数才能测试我的组件.

I need to be able to mock the activated route parameters to be able to test my component.

这是我迄今为止最好的尝试,但没有奏效.

Here's my best attempt so far, but it doesn't work.

{ provide: ActivatedRoute, useValue: { params: [ { 'id': 1 } ] } },

ActivatedRoute 在实际组件中使用如下:

The ActivatedRoute is used in the actual component like this:

this.route.params.subscribe(params => {
    this.stateId = +params['id'];

    this.stateService.getState(this.stateId).then(state => {
        this.state = state;
    });
});

我当前尝试的错误很简单:

The error I get with my current attempt is simply:

TypeError: undefined 不是构造函数(评估this.route.params.subscribe")

任何帮助将不胜感激.

推荐答案

您的模拟必须反映它要替换的对象.你 .subscribe 因为它返回一个 observable,而不仅仅是对象,所以你的模拟值也应该:

Your mock must reflect the object it's replacing. You .subscribe because it returns an observable, not just the object, so your mock value should too:

import { Observable } from 'rxjs/Rx';

...

{ provide: ActivatedRoute, useValue: { 'params': Observable.from([{ 'id': 1 }]) } }

这篇关于Angular2 RC5 模拟激活路由参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:36