Angular 8中如何跳转回上一页?及相关方法差异解析
Great question! Let’s break down each pair of methods clearly so you can pick the right one for your multi-entry component scenario:
1. window.history.back() vs this.location.back()
First up, let’s clarify the relationship between these two:
- If you’re using a framework like Angular,
this.location.back()refers to the framework’s built-in Location service method. Under the hood, it still calls the raw browser APIwindow.history.back()—but adds framework-specific benefits, like triggering routing events that your app can react to, and playing nicely with the framework’s change detection lifecycle. window.history.back()is the plain browser API: it directly tells the browser to navigate back one step in its session history stack, no framework wrapping involved.
For most framework-based projects, using this.location.back() is preferable because it keeps your navigation aligned with the framework’s ecosystem. But functionally, both methods achieve the same core goal: taking the user to the previous page in their browsing history.
2. window.history.back() vs this.router.navigate('../')
This is where the critical differences lie, especially for your multi-entry component use case:
window.history.back()is history-driven: It relies on the browser’s actual navigation history. If a user arrived at your component from Page A, it sends them back to Page A; if they came from Page B, it sends them back to Page B. This is exactly what you need for a component with multiple entry points—it respects the user’s actual journey.this.router.navigate('../')is route-hierarchy-driven: It calculates the target route based on the current route’s structure, not the user’s navigation history. For example:- If your component lives at
/dashboard/detail,../will always take you to/dashboard—even if the user originally came from/profile. - If your component is a top-level route like
/detail,../will jump to the root route (/), which is not what you want if the user came from another top-level page like/settings.
- If your component lives at
So for your scenario where the component is accessed from multiple pages, window.history.back() (or your framework’s wrapped version like this.location.back()) is the correct choice—it ensures users are sent back to wherever they came from, rather than a fixed relative route.
内容的提问来源于stack exchange,提问作者Ramya

