简体   繁体   中英

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.

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);
            }
        });
    }
}

storing the last route in local storage seems like a good fit here, since this shouldn't be sensitive data (unless your routes contain sensitive data). this avoids having to make network requests on each route change, or on initial load.

There are two downsides to this approach

  1. local storage doesn't persist across multiple devices.
  2. a user can always manually clear out what's in their local storage. but these would be for users that want to spend the time doing this.

For the sake of completeness, I'll also mention that you could use a cookie to store this data. Though, I would recommend local storage over cookie for this type data. keeping in mind that cookies suffer from the same downside as listed in point 2 above.

if the requirements give you leeway where the above aren't concerns, I suggest local storage. However, if the requirement for maintaining the last visited page is critical to the application, there is no avoiding the extra HTTP requests as you are persisting state at this point. In this scenario, I would suggest explaining the trade off to the stakeholders to see if these use cases are acceptable.

Good luck

老实说,我认为每次更改URL时存储URL都是最有效的解决方案,因为确定用户何时停止使用该应用程序更为复杂,并且需要考虑许多用例。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM