简体   繁体   中英

How to go back to certain page with angular router (angular 6)?

In my application I have what you would call a homepage and a finish page. In between those pages there could be anywhere from 2 - 4 screen depending on user interaction. Once the user reaches the final page and completes it I'm wanting the application to always go back to the homepage.

On other instances of this in my application I'm using window.history.go(-1) to go back a page, but since this flow can be variable I'm looking for the best way to go back to the homepage not knowing whether it is back 2 or 4 pages in the history.

Whats the best way to approach a situation like this using angular 6?

You can use navigateByUrl method of the Router in your compoent like this:

import {Router} from '@angular/router';

constructor(private router: Router) {}

navigateToHomepage() {
  this.router.navigateByUrl('/homepage');
}

Regarding going back one or several pages what you could do is to add BACK button somewhere on your page, that will programmatically sent user back one page at a time from the location history. Angular has Location service for these types of situations:

import {Location} from '@angular/common';

constructor(private location: Location) {}

goBack() {
  this.location.back();
}

Location service docs: https://angular.io/api/common/Location

Use an AuthGuard on all routes that aren't the homepage, and store a value in a service. When you complete the final page, you set the value in the service as having been completed the final stage. Get the AuthGuard to check that value in the service and if it's been marked as completed then you return false on the CanActivate function.

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