1
@RouteConfig([
{
    path: '/login',
    name: 'Login',
    component: LoginComponent
},
{
    path: '/search',
    name: 'Search',
    component: SearchComponent,
    needAuth: true
},
{
    path: '/result/:searchString',
    name: 'Result',
    component: ResultComponent,
    needAuth: true
},
{path: '/**', redirectTo: ['Login']}
])

I have a config as this, how can I detect current route object like;

{
    path: '/result/:searchString',
    name: 'Result',
    component: ResultComponent,
    needAuth: true
}

for route restriction when user not logged in.

I want to make like this;

export class AppComponent {
constructor(private _authService:AuthenticationService) {
    if (this._authService.getUser() != null && CURRENT ROUTE OBJECT's needAuth PROPERTY is TRUE) {
        this._router.navigate(['Search'])
    } else {
        this._router.navigate(['Login'])
    }
}

}

All kind of helps are welcome.

**************UPDATE********************

I found this solution

        this._router.subscribe((url) => {
        this._router.recognize(url).then((instruction) => {
            if(this._authService.getUser() == null && instruction.component.routeData.data.needAuth) {
                this._router.navigate(['Login'])
            }

            if(this._authService.getUser() !=null && !instruction.component.routeData.data.needAuth) {
                this._router.navigate(['Search'])
            }
        });
    });
Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
İsmail Şener
  • 413
  • 2
  • 6
  • 14

2 Answers2

0

Instead of

needAuth: true

in the RouteConfig use

data: {needAuth: true}

then inject it

constructor(private routeData: RouteData) {
  if(routeData.needAuth) {
    ...
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

I think that you could extend the RouterOutlet class to intercept the route activation in a global way:

import {Directive} from 'angular2/core';
import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router';

@Directive({
  selector: 'router-outlet'
})

export class MyOwnRouterOutlet extends RouterOutlet {
  (...)

  activate(oldInstruction: ComponentInstruction) {
    var url = this.parentRouter.lastNavigationAttempt;
    console.log('attemping to nav');
    if (oldInstruction.routeData.needAuth && !this.authService.loggedIn){
      var newInstruction = new ComponentInstruction('Login', [], new RouteData(), Login, false, 1);
      return super.activate(newInstruction);
    } else {
      return super.activate(oldInstruction);
    }
  }
}

You need to configure routes this way:

{
  path: '/result/:searchString',
  name: 'Result',
  component: ResultComponent,
  data: {
    needAuth: true
  }
}

See these links for more details:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360