好吧,這是我剝離出來例子應該說明這一點:
@Injectable()
export class AuthGuardService implements CanActivate
{
toUrl;
constructor(public authenticationService: AuthenticationService,
public router: Router)
{
}
canActivate(route, state): boolean
{
this.toUrl = state.url; //This is the url where its going
if (this.authenticationService.isLoggedIn()) return true;
this.router.navigate(['/login', {redirect: this.toUrl}]);
}
}
,並在登錄組件使用ngOnInit來檢查任何重定向ulrs:
export class LoginComponent
{
redirect;
constructor(
private authenticationService: AuthenticationService,
private route: ActivatedRoute,
private router: Router)
{
}
ngOnInit()
{
this.redirect = this.route.snapshot.params['redirect'];
}
logIn(): void
{
this.authenticationService
.login(this.searchParams)
.subscribe(
() =>
{
this.logInSuccess();
},
error =>
{
this.logInFail(error)
})
}
logInSuccess(): void
{
if (this.redirect)
{
this.router.navigateByUrl(this.redirect);
}
else
{
this.router.navigate([''])
}
}
}
所以這樣的路線警衛的作品是,它擊中了警衛的canActivate方法,以確定用戶是否已經過身份驗證。在這種方法中,我試圖抓取this.router.url,但它等於用戶點擊安全路線鏈接時的路線,而不是新路線。地址欄中的URL是當前路由,而不是新的安全路由。所以我無法知道用戶點擊了哪個安全路線。或者至少我不認爲我會這樣做,我希望有人能告訴我如何獲得新的路線,以便我可以完全按照您的建議進行操作。 – Eddie
我在我的應用程序中實現這一點意味着要做一段時間。我分享我是如何做到的。 –
我明白你的意思了,我一直在努力尋找新路線。似乎無法在任何地方找到它。 –