0

I have following setup with components.
Boot.ts
|__Home.ts
|__Aboutus.ts
|__contactus.ts

boot.ts

directives:[AuthOutlet,HomeCmp,ROUTER_DIRECTIVES,ClientCmp,AboutUsCmp,Login],
template: `
            <auth-outlet></auth-outlet>
          `
@RouteConfig([
  {path:'/Home', name: 'Home', component: HomeCmp, useAsDefault: true}
  {path:'/AboutUs', name: 'AboutUs', component: AboutUsCmp}
  {path:'/Clients', name: 'Client', component: ClientCmp}
  {path:'/Login', name: 'Login', component: Login}
])

authOutlet.ts

import {Directive, Attribute, DynamicComponentLoader, ElementRef} from 'angular2/core';
import {RouterOutlet, Router, ComponentInstruction, RouteData } from 'angular2/router';
import {AuthService} from 'Angular/src/authService.ts';
import {Login} from 'Angular/src/Login/login.ts';

@Directive({
    selector: 'auth-outlet'
})
export class AuthOutlet extends RouterOutlet {
  publicRoutes: any;
  private parentRouter: Router;
  private authService: AuthService;
  constructor(_elementRef: ElementRef, _loader: DynamicComponentLoader, _parentRouter: Router,
      @Attribute('name') nameAttr: string, _authService: AuthService) {

      super(_elementRef, _loader, _parentRouter, nameAttr);
      this.parentRouter = _parentRouter;
      this.authService = _authService;
      this.publicRoutes = {
          '/AboutUs': true,
          '/Home':true
      };
  }
   activate(oldInstruction: ComponentInstruction) {
        console.log(this.parentRouter);

        // here I get this.parentRouter object.

        var url = this.parentRouter.lastNavigationAttempt;
      ________________________________________________________________
      here I get blank url because  lastNavigationAttempt is always " " (blank).
      ___________________________________________________________
      I want to have some value in url so further I can do something.
      ________________________________________________________________
      I can't figure out what is the problem and why????Is anything missing?
      _______________________________________________________________

        console.log('redirecting to '  + url);
        var user=JSON.parse(localStorage.getItem('UserData');
        console.log('User Data');
        console.log(user);
        console.log(this.publicRoutes[url]);
        if(user!=null)
        {
            if (!this.publicRoutes[url] && !user.loggedIn){
                var newInstruction = new ComponentInstruction('Login', [], new RouteData(), Login, false, 1);
                console.log(newInstruction);
                return super.activate(newInstruction);
            } else {
            console.log(oldInstruction);
                return super.activate(oldInstruction);
            }
        }
        else
        {
              console.log('Outlet - bye bye logout');
               var newInstruction = new ComponentInstruction('Login', [], new RouteData(), Login, false, 1);
                console.log(newInstruction);
                return super.activate(newInstruction 
        }
    }
}

If I start getting url value then I can use it in IF condition used below somewhere. Is there any other way to do it ? or what should I do to get that url value?

micronyks
  • 54,797
  • 15
  • 112
  • 146

2 Answers2

0

You are getting a blank url because you are visiting the root of your app probably.

lastNavigationAttempt is not documented yet (https://angular.io/docs/ts/latest/api/router/Router-class.html) but as far as I know it is not updated when navigating inside your web application. However it is updated when navigating by url.

It might be a good idea to use the CanActivate decorator (https://angular.io/docs/ts/latest/api/router/CanActivate-decorator.html). CanActivate can determine if a component is accessible before it is initialised.

It is a decorator to you can use it like this:

@Component({
    selector: 'client', 
    template: `<h1>Client</h1>`
})

@CanActivate(isLoggedIn())

class ClientCmp {
    ...
}
  • But this is something that has to be written in every compoonent. I don't wanna do that. What I also prefer is to have a common code for redirection and global setting related to routing. I'd prefer to use @CanActivate if I want to do something at particular component. – micronyks Feb 24 '16 at 13:29
0

In my team we also adopted the custom router outlet approach in order to implement private/protected routes. Our implementation is based off of the examples given by user @Blacksonic in a number of answers & blog posts. One example is this SO answer, where the core method is something like:

activate(instruction: ComponentInstruction) {
  if (this.applyYourAuthLogicHere(instruction.urlPath)) {
    return super.activate(instruction);
  }

  this.parentRouter.navigate(['Your-Login-Route-Name']);
}

Although I must flag one warning: this works for Angular betas, pre RC1. After RC1 went out, it seems that router implementation is going under quite some changes, so I'm not sure the router outlet API for customization is still the same.

Community
  • 1
  • 1
superjos
  • 12,189
  • 6
  • 89
  • 134