首页 > 解决方案 > Angular 4: Redirecting user to last visited page in previous session on login

问题描述

I have a task of redirecting an user to the last visited page after s/he logs in. Now I clearly have to store the router Url of the last visited page in my backend. My question is how can I do that so that I do not have to make a lot of backend calls? I am using Angular 4 + Spring boot. Please help me with suggestions and ideas.

标签: javascriptangularspring

解决方案


Save the last navigation status in local storage, which you can refer to later. For an example, you add something like following to your app component.

export class AppComponent {
    constructor(private router: Router) {
        const lastVisitedUrl: string = localStorage.getItem('last_visited_url');
        localStorage.removeItem('last_visited_url');
        if (lastVisitedUrl) {
            this.router.navigateByUrl(lastVisitedUrl);
        }
        router.events.subscribe((event: RouterEvent) => {
            if (event instanceof NavigationEnd) {
                localStorage.setItem('last_visited_url', event.url);
            }
        });
    }
}

推荐阅读