Angular中的路由器提供了一种导航回退的方法,但默认情况下,导航回退不会刷新视图。要实现在导航回退时刷新视图,你可以使用以下方法。
NavigationStart
事件和Router
服务来监听导航开始事件。下面是一个示例代码:
首先,创建一个RefreshGuard
守卫来监听导航开始事件和判断后退操作:
import { Injectable } from '@angular/core';
import { CanActivate, Router, NavigationStart } from '@angular/router';
import { filter } from 'rxjs/operators';
@Injectable()
export class RefreshGuard implements CanActivate {
constructor(private router: Router) {}
canActivate() {
return this.router.events.pipe(
filter(event => event instanceof NavigationStart)
).subscribe((event: NavigationStart) => {
if (event.navigationTrigger === 'popstate') {
// 后退操作
const urlWithRefresh = event.url + (event.url.includes('?') ? '&' : '?') + 'refresh=true';
this.router.navigateByUrl(urlWithRefresh);
}
});
}
}
然后,在你的路由配置中使用RefreshGuard
守卫:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { YourComponent } from './your-component.component';
import { RefreshGuard } from './refresh.guard';
const routes: Routes = [
{
path: 'your-component',
component: YourComponent,
canActivate: [RefreshGuard]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
最后,在YourComponent
组件中检查查询参数来决定是否刷新视图:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
refresh: boolean;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.queryParams.subscribe(params => {
this.refresh = params['refresh'] === 'true';
if (this.refresh) {
// 执行刷新操作
}
});
}
}
现在,当你点击浏览器的后退按钮时,路由器将会刷新YourComponent
组件的视图。
下一篇:Angular后退导航