只要承诺尚未解决,我就想阻止访问路线。另外,我想将该承诺的返回值传递给路由组件。
Several https://stackoverflow.com/questions/36260780/angular-2-resolve-root-component-before-instantiating-child-components posts https://stackoverflow.com/questions/34734367/angular-2-router-resolve-server-request-before-opening-a-component所以建议使用OnActivate
为此的接口。这文档 https://angular.io/docs/ts/latest/api/router/OnActivate-interface.html说:“如果routerOnActivate
返回一个承诺,路由更改将等到承诺解决后再实例化并激活子组件”听起来很完美,只是路线仍然立即激活......(是不是因为它是子组件将等待 Promise 的 Route2,而不是 Route2 组件本身??)
See https://plnkr.co/edit/ipKrOgfRj0vKk8ZejH5v?p=preview https://plnkr.co/edit/ipKrOgfRj0vKk8ZejH5v?p=preview。 Route2 组件实现了OnActivate
界面,但是当您单击 Route2 链接时,Route2组件立即激活。但是,URL 确实更新为/route2
只有在承诺解决之后。 (在单独的窗口中启动 Plunker 看看我的意思。)现在我不太关心 URL,Route2 组件根本不应该实例化,直到承诺得到解决。
我的另一个策略是使用@CanActivate
装饰师。它更适合我的目的,因为“路由器调用它来确定组件是否可以实例化为导航的一部分”。
这里的问题是如何从 Promise 中传递数据@CanActivate
组件的装饰器?
我见过人们将他们的数据写入next
装饰器的参数,并在next
的参数routerOnActivate
method.
例如在next.params
(here https://stackoverflow.com/a/34159997/1153681):
@CanActivate((next) => {
return messageService.getMessage()
.then((message) => {
next.params.message = message;
return true;
});
})
export class MyComponent implements OnActivate {
routerOnActivate(next) {
this.message = next.params.message;
}
}
Or in next.routeData.data
(here https://stackoverflow.com/a/34927099/1153681).
But the 文档 https://angular.io/docs/ts/latest/api/router/ComponentInstruction-interface.html说 ComponentInstruction 对象“应该被视为不可变的”。这很令人困惑。
这是最好的方法吗?
也许当前状态的路由器还没有最终确定,当稳定的 Angular 2 发布时会有更好的方法?