使用Router将对象传递给Angular2组件

时间:2016-02-13 17:28:00

标签: javascript typescript angular

我正在寻找Angular2及其Routing系统。我正在创建项目向导' @Component与孩子在一起' @Component使用@RouteConfig,看起来像这样:

const enum State {
    welcome, basicData, groupsData, overview
}

const enum Condition {
    back
}

@Component({
    selector: 'router-outlet',
    templateUrl: '/app/templates/wizard/project/project-wizard-container.html',
    directives: [
        ROUTER_DIRECTIVES,
    ],
})

@RouteConfig([
    { path: '/',         name: 'ProjectWizardWelcome',  component: ProjectWizardWelcomeComponent, useAsDefault: true },
    { path: '/step2',    name: 'ProjectWizardStep2',    component: ProjectWizardStep2Component    },
    { path: '/step3',    name: 'ProjectWizardStep3',    component: ProjectWizardStep3Component    },
    { path: '/overview', name: 'ProjectWizardOverview', component: ProjectWizardOverviewComponent },
])

export class ProjectWizardComponent {

    mock: Mock = new Mock();

    private mapping: {key: State, value: string}[] = [
        { key: State.welcome,    value: 'ProjectWizardWelcome'  },
        { key: State.basicData,  value: 'ProjectWizardStep2'    },
        { key: State.groupsData, value: 'ProjectWizardStep3'    },
        { key: State.overview,   value: 'ProjectWizardOverview' },
    ];

    private transitions: FSM.Transition<State, Condition>[] = [
        { from: State.welcome,    conditions: [],               to: State.basicData  },
        { from: State.basicData,  conditions: [Condition.back], to: State.welcome    },
        { from: State.basicData,  conditions: [],               to: State.groupsData },
        { from: State.groupsData, conditions: [Condition.back], to: State.basicData  },
        { from: State.groupsData, conditions: [],               to: State.overview   },
        { from: State.overview,   conditions: [Condition.back], to: State.groupsData },
    ];

    private fsm: FSM<State, Condition> = new FSM(State.welcome, this.transitions);

    constructor(
        private _router: Router,
        private _routeParams: RouteParams) {
    }

    onPrev(): void {
        var prevState = this.fsm.apply([Condition.back]).get();
        var prevRoute = this.mapping[prevState].value;
        this._router.navigateByInstruction(this._router.generate([prevRoute]), true);
    }

    onNext(): void {
        var nextState: State = this.fsm.apply([]).get();
        var nextRoute = this.mapping[nextState].value;
        this._router.navigateByInstruction(this._router.generate([nextRoute]), true);
    }

    onCancel(): void {
        this._router.navigate(['Welcome']);
    }

}

我需要在“孩子”之间分享一个Mock个对象。组件,我想了解我的选择。我目前的理解是:

  1. 可以使用容器对象共享它,@Injectable就像某些Service
  2. 使用RouterData。在这种情况下,我需要从url解组数据。
  3. 但是有没有其他方法可以直接使用路由器将此对象传递给@Component

1 个答案:

答案 0 :(得分:2)

不,这两个是可用的选项。我建议使用共享服务。