Hands-On Data Structures and Algorithms with JavaScript
上QQ阅读APP看书,第一时间看更新

Navigating between states

To add logic to the back button from here on is relatively simpler. When the user clicks on the Back button, we will navigate to the previous state of the application from the stack. If the stack was empty when the user clicks the Back button, meaning that the user is at the starting state, then we set it back into the stack because we do the pop() operation to determine the current state of the stack.

goBack() {
let current = this.stack.pop();
let prev = this.stack.peek();

if (prev) {
this.stack.pop();

// angular provides nice little method to
// transition between the states using just the url if needed.
this.router.navigateByUrl(prev.urlAfterRedirects);

} else {
this.stack.push(current);
}
}

Note here that we are using urlAfterRedirects instead of plain urlThis is because we do not care about all the hops a particular URL made before reaching its final form, so we can skip all the redirected paths that it encountered earlier and send the user directly to the final URL after the redirects. All we need is the final state to which we need to navigate our user because that's where they were before navigating to the current state.