Angular Router.navigate末尾的调用函数

Angular Router.navigate末尾的调用函数,angular,Angular,我想在用户登录后调用某个函数。用户可以从任何页面登录,成功登录后,用户将重定向回他们正在浏览的上一页 我正在使用重定向到页面 在寻找一段时间后,这似乎是一个可行的选择,但它适用于所有路由器事件,而不仅仅是一个特定的事件 我的login.component.ts如下所示: // ... this.authenticationService.login(this.credentials) .pipe(first()) .subscribe( data => { th

我想在用户登录后调用某个函数。用户可以从任何页面登录,成功登录后,用户将重定向回他们正在浏览的上一页

我正在使用重定向到页面

在寻找一段时间后,这似乎是一个可行的选择,但它适用于所有路由器事件,而不仅仅是一个特定的事件

我的
login.component.ts
如下所示:

// ...
this.authenticationService.login(this.credentials)
  .pipe(first())
  .subscribe(
    data => {
      this.router.navigate([this.returnUrl]);
      // Need to call a function `doSomething()` here.
    },
    error => {
      // Implement error handling
    });
// ...
我知道这不是一个承诺,但我正在寻找类似的东西:

this.router.navigate([this.returnUrl])
  .then(this.doSomething()); // or .pipe()

你可能想研究一下使用某种。。您可以在正在导航的组件中执行OnDestroy。或者您正在导航的组件中的OnInit

我认为最简单的事情就是只听你提到的
NavigationEnd
事件,但在它发生后停止听

this.authenticationService.login(this.credentials)
  .pipe(first())
  .subscribe(
    data => {
      this.router.navigate([this.returnUrl]);
      this.router.events.pipe(
        first(evt => evt instanceof NavigationEnd)
      ).subscribe(() => {
        this.doSomething(); 
      });
    },
    error => {
      // Implement error handling
    });
我认为这是正确和安全的做法,因为你知道:

  • 将有
    NavigationEnd
    事件即将发生
  • 它将是触发代码的正确事件
  • 发生这种情况后,你可以停止倾听
  • 这个怎么样

    this.router.events.subscribe(event => {
        if (event instanceof NavigationEnd) {
            if(event.url === "your-route") {
                //do your thing
            }
        }
    });
    
    您可以使用返回承诺的

    this.router.navigateByUrl(this.returnUrl).then(this.doSomething());
    

    非常适合我的用例!API文档中遗漏了这一点。这可能发生在任何组件到任何其他组件之间。我不想为此在每个组件中添加函数。