Javascript 如何在单击浏览器后退按钮时将用户重定向到特定页面

Javascript 如何在单击浏览器后退按钮时将用户重定向到特定页面,javascript,angular,routing,Javascript,Angular,Routing,因此,我必须“禁用”在几个路由上单击浏览器后退按钮,因为对backeng的请求已经发送,创建大量类似于api的请求是不一致的。基本上我用的是 this.location.onPopState(() => { console.log('pressed back!'); this.router.navigateByUrl('url', { skipLocationChange: true }) }); 在检测返回按钮的构造函数中,问题是当我单击返回时,我没有重定向到所需的页面,而是重

因此,我必须“禁用”在几个路由上单击浏览器后退按钮,因为对backeng的请求已经发送,创建大量类似于api的请求是不一致的。基本上我用的是

this.location.onPopState(() => {
  console.log('pressed back!');
  this.router.navigateByUrl('url', { skipLocationChange: true })
});
在检测返回按钮的构造函数中,问题是当我单击返回时,我没有重定向到所需的页面,而是重定向到上一个页面。我试过
location.here=url但它会重新加载窗口,并在一秒钟内仍显示上一页。

如果您有任何建议,我将非常感谢您的帮助。

我认为阻止后退按钮不是一个好主意。您可以对请求使用缓存机制,这样它不会每次都向服务器发送请求,而是获取最新的响应。请检查此示例:

const URL = 'https://api.punkapi.com/v2/beers';
@Injectable({
  providedIn: 'root'
})
export class HttpService {
  public responseCache = new Map();constructor(private http: HttpClient) {}public getBeerList(): Observable<any> {
    const beersFromCache = this.responseCache.get(URL);
    if (beersFromCache) {
      return of(beersFromCache);
    }
    const response = this.http.get<any>(URL);
    response.subscribe(beers => this.responseCache.set(URL, beers));
    return response;
  }
}
这将适用于所有导航,如果您仍然只需要背面,则需要检查您要访问的URL是否与前面的URL相同

我的服务

previousUrl: string;
constructor(router: Router) {
  router.events
    .filter(event => event instanceof NavigationEnd)
    .subscribe(e => {
      console.log('prev:', this.previousUrl);
      this.previousUrl = e.url;
    });
} 
在my-guard.guard.ts中

canActivate(route: ActivatedRouteSnapshot) {
  return route.url !== this.myService.previousUrl;
}
参考资料和更多信息:

canActivate(route: ActivatedRouteSnapshot) {
  return route.url !== this.myService.previousUrl;
}