路由参数订阅在 Angular2 中未可靠触发
Route Parameter Subscription not triggered reliably in Angular2
我正在开发一个基于 Angular2 的测验,其中包含一些 'static' 组件(主页、常见问题解答等)和一个代表测验卡片的组件。
我的设置使用带有占位符的路由,如下所示:
{
path: 'quiz/:questionPage',
component: QuizComponent
},
这里questionPage
应该是数字...
为了切换测验卡片,我正在更改位置并展示新卡片:
import { Location } from '@angular/common';
import { ActivatedRoute } from '@angular/router'
...
constructor (
private route: ActivatedRoute,
private location: Location) {...}
...
showQuestion(next) {
this.location.go ('quiz/' + next);
this.showQuestion (next);
}
要在 QuizComponent
中实现浏览器 back/forward(除了问答卡中的 next/prev)我想我可以只订阅 [=14= 中的路由参数]的构造函数:
this.route.params.subscribe(params => {
console.log ("found params: ", params);
});
效果非常好:点击 next/prev 更新了卡片,使用浏览器 back/forward 我可以浏览卡片的历史记录。我认为一切都很完美,但我只是发现至少有一个用例不起作用:
如果我返回(无论多久)然后单击新内容,后退按钮只会更新位置(地址栏中的url)但是上面的订阅没有被触发(因此卡片不会得到更新)。如果我再点击一次它又能正常工作了,但我又退了两步!?我可以再次前进以访问历史记录中的正确条目,但这当然很烦人...
所以..我做错了什么吗?也许这也是实现浏览器的一种超级愚蠢的方法-back/forward?
实际上,在阅读有关 Location I assume this is indeed the problem. This is a service for interacting with the browsers URL, you should use the Router 在您的应用程序内导航的文档后。
如文档中所述:
Use Location only if you need to interact with or create normalized
URLs outside of routing.
因此,如果您使用以下内容进行导航:
this.router.navigate(['quiz', next]);
它应该按预期工作。
我正在开发一个基于 Angular2 的测验,其中包含一些 'static' 组件(主页、常见问题解答等)和一个代表测验卡片的组件。 我的设置使用带有占位符的路由,如下所示:
{
path: 'quiz/:questionPage',
component: QuizComponent
},
这里questionPage
应该是数字...
为了切换测验卡片,我正在更改位置并展示新卡片:
import { Location } from '@angular/common';
import { ActivatedRoute } from '@angular/router'
...
constructor (
private route: ActivatedRoute,
private location: Location) {...}
...
showQuestion(next) {
this.location.go ('quiz/' + next);
this.showQuestion (next);
}
要在 QuizComponent
中实现浏览器 back/forward(除了问答卡中的 next/prev)我想我可以只订阅 [=14= 中的路由参数]的构造函数:
this.route.params.subscribe(params => {
console.log ("found params: ", params);
});
效果非常好:点击 next/prev 更新了卡片,使用浏览器 back/forward 我可以浏览卡片的历史记录。我认为一切都很完美,但我只是发现至少有一个用例不起作用:
如果我返回(无论多久)然后单击新内容,后退按钮只会更新位置(地址栏中的url)但是上面的订阅没有被触发(因此卡片不会得到更新)。如果我再点击一次它又能正常工作了,但我又退了两步!?我可以再次前进以访问历史记录中的正确条目,但这当然很烦人...
所以..我做错了什么吗?也许这也是实现浏览器的一种超级愚蠢的方法-back/forward?
实际上,在阅读有关 Location I assume this is indeed the problem. This is a service for interacting with the browsers URL, you should use the Router 在您的应用程序内导航的文档后。
如文档中所述:
Use Location only if you need to interact with or create normalized URLs outside of routing.
因此,如果您使用以下内容进行导航:
this.router.navigate(['quiz', next]);
它应该按预期工作。