我目前正在处理的项目,我想将returnUrl应用于登录。我在这里附上了代码。当我尝试在ngOnInit()中初始化returnUrl时,它无法正常工作。但是如果我在login方法中初始化returnUrl,它就可以了。这可能是什么问题?
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { LoginUser } from '../_models/LoginUser';
import { AlertifyService } from '../_services/alertify.service';
import { AuthService } from '../_services/auth.service';
@Component({
selector: 'app-nav',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavBarComponent implements OnInit {
user: LoginUser = { username: '', password: '' };
photoUrl: string;
constructor(
public authService: AuthService,
private alertify: AlertifyService,
private router: Router,
private route: ActivatedRoute) { }
ngOnInit() {
this.authService.currentPhotoUrl.subscribe(photoUrl => this.photoUrl = photoUrl);
}
login() {
let returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') || '/members';
this.authService.login(this.user).subscribe(data => {
this.router.navigateByUrl(returnUrl);
}, error => {
this.alertify.error('Login Failed');
}, () => {
this.alertify.success('Login Successful');
});
}
logout() {
this.authService.userToken = null;
this.authService.currentUser = null;
localStorage.removeItem('token');
localStorage.removeItem('user');
this.alertify.message('logged out');
this.router.navigate(['/home']);
}
loggedIn() {
return this.authService.loggedIn();
}
}
答案 0 :(得分:0)
为什么不使用AuthGuard并覆盖canActivate
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
.....
.....
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}