在Angular 7中,可以使用Router
和Location
服务来实现重定向到上一个访问的页面。
首先,导入Router
和Location
服务:
import { Router, NavigationEnd } from '@angular/router';
import { Location } from '@angular/common';
然后在组件的构造函数中注入Router
和Location
服务:
constructor(private router: Router, private location: Location) { }
接下来,可以使用以下代码来重定向到上一个访问的页面:
redirectToPreviousPage() {
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.location.back();
}
});
}
在上面的代码中,我们通过订阅Router
的事件流来监听页面导航事件。当导航结束时,我们使用Location
服务的back()
方法来返回到上一个访问的页面。
最后,可以在需要的地方调用redirectToPreviousPage()
方法来执行重定向操作。
请注意,上述代码只能在用户进行页面导航后才能有效,如果用户直接输入URL或刷新页面,将无法返回到上一个访问的页面。