首页 文章

Angular 4:收回和转发浏览器按钮单击并更新页面

提问于
浏览
1

我是角度4的新手,如果用户点击后退或转发浏览器按钮,则会出现页面不刷新的问题 . url中的查询参数按历史记录更改,但页面不会刷新以前的结果 . 例如/ search?text =“ret”和后退按钮它变为/ search?text = ben&tab = doc .

需要在浏览器按钮单击时刷新“搜索”路径 . 尝试使用Location popstate事件捕获点击但无法刷新页面 .

设置window.location.href有效但重新加载页面 . ngrx路由器商店可以成为一个解决方案吗?

https://github.com/ngrx/platform/blob/v4.1.1/docs/router-store/api.md

2 回答

  • 1

    据我了解,您不需要实际刷新页面 . 这就是单页应用程序的全部内容 . 相反,尝试在 location.onPopState 处理程序中主动更改页面 . 您甚至可以在那里执行 router.navigate 或解析弹出的查询参数,获取并重新填充搜索结果 . 您已经知道新位置,因此请使用此过程中的知识 .

  • 0

    当路线's path remains the same, but the query params or route params are dynamic (change), the current component will not be destroyed and re-initialized. That is unless you flag the router to do so (Router.onSameUrlNavigation('重装') - 见https://angular.io/api/router/Router) .

    对于您的情况,您应该订阅路由的查询参数,并在每次发出新参数时做出反应 .

    例如 .

    subscriptions: Subscription[] = [];
    
    constructor(private route: ActivatedRoute) { }
    
    ngOnInit() {
    
        this.subscriptions.push(this.route.queryParamMap.subscribe(queryParamMap => {
            const text = queryParamMap.get('text');
            const doc = queryParamMap.get('doc');
    
            this.updateView(text, doc);
        }));
    }
    
    ngOnDestroy() {
        this.subscriptions.forEach(s => s.unsubscribe());
    }
    

    当您知道不需要处理动态路由/查询参数时,只使用route.snapshot作为快捷方式 .

相关问题