Переадресация на вход в систему, если требуется вход в систему перед перенаправлением на определенные URL-адреса с расширением RouterOutlet
У меня есть следующие настройки с компонентами.
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
}
}
}
Если я начну получать значение URL, то я могу использовать его в IF
условие используется ниже где-то. Есть ли другой способ сделать это? или что я должен сделать, чтобы получить значение URL?
2 ответа
В моей команде мы также приняли индивидуальный подход к маршрутизатору для реализации частных / защищенных маршрутов. Наша реализация основана на примерах, приведенных пользователем @Blacksonic во многих ответах и сообщениях в блоге. Одним из примеров является этот SO-ответ, где основной метод выглядит примерно так:
activate(instruction: ComponentInstruction) {
if (this.applyYourAuthLogicHere(instruction.urlPath)) {
return super.activate(instruction);
}
this.parentRouter.navigate(['Your-Login-Route-Name']);
}
Хотя я должен отметить одно предупреждение: это работает для угловых бета-версий, предварительно RC1. После выхода RC1 кажется, что реализация маршрутизатора претерпела некоторые изменения, поэтому я не уверен, что API настройки маршрутизатора для настройки остается прежним.
Вы получаете пустой URL, потому что вы, вероятно, посещаете корень своего приложения.
lastNavigationAttempt еще не задокументирован ( https://angular.io/docs/ts/latest/api/router/Router-class.html), но, насколько я знаю, он не обновляется при навигации внутри вашего веб-приложения. Однако он обновляется при навигации по URL.
Возможно, было бы неплохо использовать декоратор CanActivate ( https://angular.io/docs/ts/latest/api/router/CanActivate-decorator.html). CanActivate может определить, доступен ли компонент до его инициализации.
Это декоратор, чтобы вы могли использовать его так:
@Component({
selector: 'client',
template: `<h1>Client</h1>`
})
@CanActivate(isLoggedIn())
class ClientCmp {
...
}