I'm trying to redirect the user to the previous road after they successfully log in.
My auth.guard.ts
const currentUser = this.authenticationService.currentUserValue;
if (currentUser) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
return false;
sets up the proper returnUrl
Then my login.component.ts
[...]
// get return url from route parameters or default to '/'
this.route.queryParams
.subscribe(params => {
this.returnUrl = params['redirectUrl'] || '/'
console.log(this.returnUrl)
console.log(params)
} );
[...]
this.authenticationService.login(this.f.email.value, this.f.password.value)
.pipe(first())
.subscribe(
data => {
//TODO: navigate returns false
this.router.navigate([this.returnUrl]).then(nav => {
console.log(nav); // true if navigation is successful
}, err => {
console.log(err) // when there's an error
});
},
error => {
this.spinner = false;
this.submitted = false;
this.invalid = true;
this.loading = false;
},
() => {
this.spinner = false;
this.submitted = false;
});
Here, the navigate returns false and does nothing else. I've tried to see if this.returnUrl is set correctly and indeed it is. So I don't know what can cause the issue. If I set this.router.navigate['/something'] then it works fine.
login.component.ts
In ngOnInit()
this.route.queryParams.subscribe(
params => (this.returnUrl = params.return || '/')
);
Then
this.authenticationService.login(this.f.email.value, this.f.password.value)
.pipe(first())
.subscribe(
data => {
this.router.navigate([this.returnUrl]);
},
error => {
this.spinner = false;
this.submitted = false;
this.invalid = true;
this.loading = false;
}
});
Here you used returnUrl as your queryParam
this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
But you trying to get redirectUrl
params['redirectUrl']
Change params['redirectUrl']
to params['returnUrl']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.