1

How i can get name of current route? Not URL part, but route name or alias.

I want to do redirect inside CanActivate hook. If this hook return false, while i stayed on root route ('/'), i need to reload page, because standart Route.navigate on same URL did not reload page.

Also i looked for similar questions on StackOverflow, but did not find any solution. All few solution based on Location url parsing, but this not what i want.

1 Answers1

3

beta.x router and RC.1 router-deprecated

I guess this is what you are looking for https://github.com/brandonroberts/angular/commit/c1d499d567d88baa10fa964459feb15b267e8c8b. Currently this seems to be only available using the private _currentInstruction field of the Router.

See also https://github.com/angular/angular/issues/5335#issuecomment-170088933

in the meantime, if you want the current route instruction, you can subscribe to the router for URL updates and convert that into an instruction.

import {Injectable} from 'angular2/core';
import {Router, Instruction} from 'angular2/router';

@Injectable()
export class RouterState {
  _current: Instruction;

  constructor(public router: Router, location: Location) {
    // subscribe to router url updates
    router.subscribe((url) => {
      // convert the current url into an instruction
      this._getInstruction(url);
    });
  }

  private _getInstruction(url) {
    this.router.recognize(url).then((ins) => {
      if (ins) {
        // Store the current route instruction
        this._current = ins;
      }
    });
  }

  current() {
    // return current instruction
    return this._current;
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567