要在Angular 9中实现重定向到相同的URL并刷新页面,同时只调用当前页面的API调用,你可以使用Router
和Location
服务来实现。
首先,确保你已经导入了Router
和Location
服务:
import { Router } from '@angular/router';
import { Location } from '@angular/common';
然后在你的组件中注入这些服务:
constructor(private router: Router, private location: Location) { }
接下来,你可以使用router.navigate
方法来重定向到相同的URL,并传递{ skipLocationChange: true }
选项:
this.router.navigate([this.location.path()], { skipLocationChange: true });
然后,你可以使用location.replaceState
方法来替换当前的URL,并强制刷新页面:
this.location.replaceState(this.router.url);
window.location.reload();
完整的代码示例:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
@Component({
selector: 'app-example',
template: `
`,
})
export class ExampleComponent {
constructor(private router: Router, private location: Location) { }
refreshPage() {
this.router.navigate([this.location.path()], { skipLocationChange: true });
this.location.replaceState(this.router.url);
window.location.reload();
}
}
这样,当你点击"Refresh"按钮时,页面将重定向到相同的URL并刷新页面,同时只调用当前页面的API调用。