Angular2用诺言获取路线的参数 [英] Angular2 Getting route's params with promises
问题描述
嘿,我已经尝试了以下代码:
Hey I have tried that following bit of code :
constructor(private _route: ActivatedRoute) {}
ngOnInit() {
this._route.params.toPromise().then(data => {
...
})
}
但是它什么也没做.如果我将toPromise().then
替换为subscribe
,则效果很好.知道为什么它行不通吗?我在项目的许多其他地方都使用过toPromise().then
,效果很好.
However it doesn't do anyhting. If I swap toPromise().then
by subscribe
it works fine. Any idea why it wouldn't work ? I have used toPromise().then
in many other places in my project and it works just fine.
推荐答案
_route.params
发出多个事件.当路由更改仅更改路由的参数值时,路由器不会重新创建组件,而是仅发出另一个params
值.
_route.params
emits more than one event. When a route change only changes the parameter value of a route then the component is not re-created by the router but instead just another params
value emitted.
因此,使用toPromise()
可能不是一个好主意,但是有可能,例如使用first()
,以便可观察对象在第一个事件之后完成,因此,toPromise()
返回的承诺也将完成.
Therefore using toPromise()
is probably not a good idea but it's possible, for example using first()
so that the observable completes after the first event and therefore also the promise returned by toPromise()
completes.
如果没有.first()
,则当您离开路线(未验证)时,诺言便会完成.
Without .first()
the promise completes when you navigate away from the route (not verified).
constructor(private _route: ActivatedRoute) {}
ngOnInit() {
this._route.params.first().toPromise().then(data => {
...
})
}
first
需要导入.在较新的RxJs版本中,first
需要像这样pipe(first())
first
needs to be imported. In newer RxJs version first
needs to be wrapped in pipe
like this pipe(first())
这篇关于Angular2用诺言获取路线的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!