简体   繁体   English

使用 Angular 按下后退按钮时如何导航到另一条路线

[英]How do I navigate to another route when back button is pressed with Angular

I'm trying to navigate to a parent route whenever a back button is pressed in my Angular app instead of a sibling route.每当在我的 Angular 应用程序中按下后退按钮时,我都会尝试导航到父路由,而不是兄弟路由。 I have tried a few methods I saw on Stack Overflow.我尝试了一些在 Stack Overflow 上看到的方法。 the latest being this...最新的是这个...

import { Component } from '@angular/core';
import { UserService } from '../shared/User.service';
import { ActivatedRoute, Router } from '@angular/router';
import { IUser } from '../shared/User';

import { HostListener } from '@angular/core';

@Component({
  selector: 'user',
  templateUrl: "./user.component.html",
  styleUrls: ['./user.component.css']
    
})

export class userComponent {
  user: IUser
  constructor(
      private userService : userService,
      private route : ActivatedRoute,
      private router :Router
      ){}
  ngOnInit(){
    this.route.params.subscribe(val=> {
      this.user = this.userService.getuser(val['user'])
    })
  }
  @HostListener('window:popstate', ['$event'])
  onBrowserBackBtnClose(event:Event){
    console.log('Back button pressedm');
    this.router.navigate([`/users`]);
  }
}

but instead it routes to the parent and immediately goes back to the sibling route.但相反,它路由到父路由并立即返回兄弟路由。 Any advice on what to do?关于做什么的任何建议?

Try this solution, I think this will resolve your issue:试试这个解决方案,我认为这将解决您的问题:

@HostListener('window:popstate', ['$event'])
  onBrowserBackBtnClose(event:Event){
    event.preventDefault();
    console.log('Back button pressedm');
    this.router.navigate([`/users`]);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular 4 - 按下后退按钮时如何路由到特定组件? - Angular 4 - How to route to a particular component when back button is pressed? Angular 2 - 如何使用 this.router.parent.navigate('/about') 导航到另一条路线? - Angular 2 - How do I navigate to another route using this.router.parent.navigate('/about')? 按下按钮时如何将列表元素添加到 Angular? - How do I add list elements to Angular when a button is pressed? 在angular2中,您如何导航到需要id的另一条路线? - In angular2 how do you navigate to another route that requires an id? 如何通过带有查询参数的URL导航到Angular路线? - How do I navigate to an Angular route via URL with query params? 尝试通过路由器导航到另一条路线时出现角度错误? - Angular error when trying to navigate to another route via router navigate? 如何在角度2中将一条路线导航到另一条路线 - how to navigate one route to another in angular 2 当我导航到 Angular 6 中的后页时如何清除下拉列表值 - How to clear the dropdowns values when i navigate to back page in Angular 6 Angular - 如何取消从“后退”按钮触发的路径更改? - Angular - How do I cancel a Route Change triggered from the Back button? 如果 router.navigate 返回 false Angular,我如何路由到另一条路由 - How I can route to another route if router.navigate returns false Angular
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM