[英]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.