Why routerLink and router.navigate() act differently?
Asked Answered
M

1

13

When using this code in HTML:

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

it navigates correctly to '/child/(flow:step1)'!!!

When trying to use this code in Typescript:

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

it trying to navigate to wrong path '/child(flow:step1)'!!!

It just missing the slash.

Service:

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);
  }

}

Here is the Module using the Service above:

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 {

}
Macrobiotic answered 11/8, 2017 at 9:46 Comment(0)
A
22

Because routerLink uses relativeTo option implicitly:

export class RouterLink {
  ...
  get urlTree(): UrlTree {
    return this.router.createUrlTree(this.commands, {
      relativeTo: this.route, <----

You need to provide it explicitly in router.navigate:

constructor(private route: ActivatedRoute)

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

Here is plunker and the complete working code:

import { Component, NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { RouterModule, Routes, Resolve, Router, ActivatedRoute } from '@angular/router';
import { APP_BASE_HREF } from '@angular/common';

@Component({
  selector: 'my-app',
  template: `
      <div id='my-app'>
          <router-outlet></router-outlet>
      </div>
  `,
})
export class App {
  constructor() {
  }
}

@Component({
  selector: 'master-page',
  template: `
      <div id='master-page'>
          <div>Master Component</div>
          <button (click)='clickFirst()'>Inner Section 1</button>
          <button (click)='clickSecond()'>Inner Section 2</button>
          <router-outlet name='child'></router-outlet>
      </div>
  `
})
export class Master {
  constructor(private router: Router, private activeRouter: ActivatedRoute) {
  }

  clickFirst() {
    this.router.navigate([{outlets: {child: 'details1'}}], {relativeTo: this.activeRouter});
  }


  clickSecond() {
    this.router.navigate([{outlets: {child: 'details2'}}], {relativeTo: this.activeRouter});
  }
}

@Component({
  template: `
      <div>
          This content is in the "Inner" page (1)
      </div>
  `
})
export class Details1 {
  constructor() {
  }
}

@Component({
  template: `
      <div>
          This content is in the "Inner" page (2)
      </div>
  `
})
export class Details2 {
  constructor() {
  }
}

const routes: Routes = [
  {
    path: 'master',
    component: Master,
    children: [
      {
        path: 'details1',
        component: Details1,
        outlet: 'child'
      },
      {
        path: 'details2',
        component: Details2,
        outlet: 'child'
      }
    ]
  },
  {
    path: '',
    pathMatch: 'prefix',
    redirectTo: 'master'
  }
];

@NgModule({
  imports: [BrowserModule, RouterModule.forRoot(routes)],
  declarations: [App, Master, Details1, Details2],
  providers: [{
    provide: APP_BASE_HREF,
    useValue: '/'
  }],
  bootstrap: [App]
})
export class AppModule {
}
Ashram answered 11/8, 2017 at 14:44 Comment(12)
can you setup a plunker?Ashram
link here... there is a base outlet and child outlet... every click should insert component to a child outlet...Macrobiotic
@VladiIsakov, it's working fine for me. In your plunker there's a typo, you should use outletS, not outlet. I posted the working app.ts code in the question.Ashram
sorry about the typo, working for me too... in my code its still not working... it says "Error: Cannot match any routes. URL Segment: 'step1'"Macrobiotic
I don't see your code. The answer to your question is correct as demonstrated by the exampleAshram
I think that I finally got it... I'm trying to navigate in service and its not working, but when I navigate in component it works... how is that possible?Macrobiotic
you're most likely injecting wrong ActivatedRoute into a service, where is this service defined? see this answerAshram
How can I perfect it?Macrobiotic
where it's registered?Ashram
Added the module using the serviceMacrobiotic
Fixed by giving the component that using the service "providers: [FlowManagerService]"... thank you for your help :)Macrobiotic
yeah, if you define a service on the root module it will be injected root level activatedroute. you're welcome, good luckAshram

© 2022 - 2024 — McMap. All rights reserved.