要在Angular导航后删除路由片段,可以使用Location
服务中的replaceState()
方法。以下是一个代码示例:
import { Component } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
@Component({
selector: 'app-my-component',
template: `
`
})
export class MyComponent {
constructor(private location: Location, private router: Router) { }
navigateToHome() {
this.router.navigate(['/home']);
}
navigateToAbout() {
this.router.navigate(['/about']);
}
removeFragment() {
this.location.replaceState(this.router.url.split('#')[0]);
}
}
在这个示例中,Location
和Router
服务被注入到组件中。navigateToHome()
和navigateToAbout()
方法用于导航到不同的路由。removeFragment()
方法使用replaceState()
方法来删除URL中的路由片段。
请注意,replaceState()
方法会在浏览器历史记录中创建一个新的历史记录条目,因此当用户点击“后退”按钮时,将返回到没有路由片段的URL。