Issue
I have tried something like this
import { Router} from '@angular/router';
@Component({
// component's declarations here
})
class SomeComponent {
constructor(private location: Location, private private router: Router)
{}
goBack() {
if (this.location.back() === undefined)
{
this.router.navigate(['/']);
}
else
{
this.location.back();
}
}
}
The problem is if I was on say reddit.com prior to accessing my site and I call the goback() function, it will route me out of my site to reddit.com which I do not want.
I would prefer to solve this problem the angular way, rather than using window
Solution
Indeed window location will take you back to previous page. How about we only use Angular's Router. The Router has existed only in your Angular App scope, so if we were to read router events no matter how far back we go in history it will never go out of Angular scope whilst window.location
will have the location of this browser tab.
onGoBack()
will subscribe to pairwise event from to router, it will take one observable with take(1)
(so no need to unsubscribe) and then it will check your if conditions. If previousUrl is present, we will use that, otherwise go to url /
.
previousUrl: string;
onGoBack() {
this.router.events
.pipe(take(1), filter((evt: any) => evt instanceof RoutesRecognized), pairwise())
.subscribe((events: RoutesRecognized[]) => {
console.log('previous url', events[0].urlAfterRedirects);
console.log('current url', events[1].urlAfterRedirects);
this.previousUrl = events[0].urlAfterRedirects;
if (!this.previousUrl) {
this.router.navigate(['/']);
} else {
this.router.navigateByUrl(this.previousUrl);
}
});
}
Answered By - Joosep Parts
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.