I have an app, with 3 links: Home (/), Sign in (/user/sign-in) and User Detail (/user).
When user click Home, my app will be show content public
When user cl
I think you could extend router outlet to implement such processing. Something like this:
@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) {
(...)
}
activate(oldInstruction: ComponentInstruction) {
var url = this.parentRouter.lastNavigationAttempt;
console.log('attemping to nav');
if (!this.publicRoutes[url] && !this.authService.loggedIn){
var newInstruction = new ComponentInstruction('Login', [], new RouteData(), Login, false, 1);
return super.activate(newInstruction);
} else {
return super.activate(oldInstruction);
}
}
}
The activate method is called when a route will be displayed. You can add at this level your processing.
You use this directive this way un your template:
@Component({
(...)
template: '<auth-outlet></auth-outlet>',
directives: [ AuthOutlet ]
})
(...)
See these links for more details:
Another option is to use the CanActivate decorator but it's per component and can't be applies globally.
For this I'll implement authService concept and before accessing any protected route, I'll check whether user is authenticated or not.If user is not authenticated I'll redirect him to login page.There if you want cancel button too, the you can put cancel button in LOGIN Component
and when you press it you can redirect user back to previous component by using CanActive hook in Login Component). Just try to learn this and if you want any further help i'm here.
auth.ts
import {Observable} from 'rxjs/Observable';
export class Auth {
constructor() {
this.loggedIn = false;
}
login() {
this.loggedIn = true;
}
logout() {
this.loggedIn = false;
}
check() {
return Observable.of(this.loggedIn);
}
}
For further code check out,
This implementation will surely help you for your use-case.
An unofficial solution that I found to this is to throw a NavigationCancelingError
through an observable or a promise. Angular's router will catch this error type, cancel the navigation, and reset the current route. For example, this can be done in a resolve like so:
import { ActivatedRouteSnapshot, Resolve, Router } from '@angular/router';
import { NavigationCancelingError } from '@angular/router/src/shared';
import { Observable } from 'rxjs';
export class CancelingResolve implements Resolve<any> {
constructor(private router: Router) {}
resolve(route: ActivatedRouteSnapshot): Observable<any> {
this.router.navigate(['new-route']); // Router will navigate here after canceling the activated route.
return Observable.throw(new NavigationCancelingError());
}
}
Note: Works under Angular 2.3.1