为什么你认为ngOnInit 应该跑在后面?它没有
解决方案是使用路由器事件:
例如:从"/beatles/john/songs/strawberryfields" 检测到back 到"/doors/jim/girlfriend/pam" 的解决方案
Doors page --------> Beatles page.....(back tapped)----------->Doors
是:
将此方法添加到共享服务中:
public onNavigatePreviousToCurrent(pre: string, current: string ): Observable<any>
{
return this.router.events.pipe(filter(e => e instanceof NavigationEnd), pairwise(), filter((f: [any, any]) =>
{
return f[0].url.toLowerCase()
.indexOf(pre.toLowerCase()) > -1 &&
f[1].url.toLowerCase()
.indexOf(current.toLowerCase()) > -1;
}) );
}
在 Doors 页面中调用它:
ngOnInit()
{
let f = this._routingService.onNavigatePreviousToCurrent("john", "pam") //or doors or jim
.subscribe((res) =>
{
//do what you want here !!!
}, (error) =>
{
});
//don't forget to unsubscribe `f`
}
请注意,您也可以在 Doors 中使用来自 /beatles/john/songs/strawberryfields(beatles,john,songs,strawberryfields,atles)----> 的任何令牌。 (子字符串)
基本上,此方法会检测您来自哪里以及back 之后的目的地是什么。
顺便说一句,你可能想说:“好吧,我不知道我在哪里,我只想要用户点击“返回”的情况。
答案:
this._routingService.onNavigatePreviousToCurrent("/", "pam") ;
// "/" will always be present , so basically this ^ detects back from anywhere to Doors page