为什么routerLink和router.navigate()采取不同的行为?

时间:2017-08-11 09:46:09

标签: angular typescript routing routerlink

在HTML中使用此代码时:

 <button [routerLink]="[{ outlets: { flow: ['step1'] } }]">click me to show step1</button>

它正确导航到&#39; / child /(flow:step1)&#39; !!!

尝试在Typescript中使用此代码时:

this.router.navigate([{ outlets: { flow: ['step1'] } }]);

它试图导航到错误的路径&#39; / child(flow:step1)&#39; !!!

它只是错过了斜线。

服务:

import { Injectable } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { EventBusService } from '../../../services/eventBus/eventBus.service';
import { RouterService } from '../../../services/router.service';

@Injectable()
export class FlowManagerService {
  constructor(private router: Router, private r: ActivatedRoute, private     eventBus: EventBusService, private routerService: RouterService) {
  }

  initValidStep() {
    return     (parseInt(this.routerService.currentUrlName.substr(this.routerService.currentUrlName.indexOf('step'), 5).replace('step', ''), 10) === 1);
  }

  goToFirstStep() {
    this.router.navigate([{ outlets: { flow: ['step1'] } }], {relativeTo: this.r});

    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_NEXT);
    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_BACK);
  }

  next(params) {
    const currentStep = this.routerService.currentUrlName.substr(this.routerService.currentUrlName.indexOf('step'), 5).replace('step', '');

    this.eventBus.emit(this.eventBus.globalEvents.FLOW.FLOW_STEP_CHANGE, ({
      type: 'NEXT'
    }));
    this.router.navigate([{ outlets: { flow: [`step${parseInt(currentStep, 10) + 1}`, params] } }], {relativeTo: this.r});

    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_NEXT);
    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_BACK);

  }

  back(params) {
    const currentStep = this.routerService.currentUrlName.substr(this.routerService.currentUrlName.indexOf('step'), 5).replace('step', '');

    this.eventBus.emit(this.eventBus.globalEvents.FLOW.FLOW_STEP_CHANGE, ({
      type: 'NEXT'
    }));
    this.router.navigate([{ outlets: { flow: [`step${parseInt(currentStep, 10) - 1}`, params] } }], {relativeTo: this.r});

    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_NEXT);
    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_BACK);
  }

}

以下是使用上述服务的模块:

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { FlowManagerService } from './service/flowManager.service';
import { CommonModule } from '@angular/common';

@NgModule({
  providers: [FlowManagerService],
  imports: [
    RouterModule,
    CommonModule
  ]
})
export class FlowManagerModule {

}

0 个答案:

没有答案