是否存在 @angular/路由器等于ui-router中的transition.from()



我正在将角度应用程序从 ui-router升级到 @angular/router(v6(。


有一个函数想要找到上一个路由。这是使用ui-router/core

Transition实现
    const newFromName = this.transition.from().name;
    this.transition.params('from')

我删除了大部分功能,因为它不应该是相关的。

我的问题是:

是否有相当于上述两行的@angular/router

我们使用
"@uirouter/angular-hybrid": "3.1.7"
"@angular/router": "6.1.1",

注意:这与动画无关。我不想动画过渡,我只想知道上一条路线是什么。

添加澄清:一个例子是,如果我在导航到此组件之前,我处于不同的路线上,例如hello/world,然后在my/new/route中使用此代码导航到路线。我需要知道值/hello/world

您可以使用此功能,在// Exit Code中,您可以访问您来自

的路线
import { Router, NavigationStart, NavigationEnd } from '@angular/router';

...

constructor(router:Router) {
  router.events.subscribe(e => {
    if(e instanceof NavigationStart) {
      // Init Code
    }
    if(e instanceof NavigationEnd) {
      // Exit Code
    }
  }
});

方法1:创建服务

@Injectable()   
export class RouterState {
  private routeHistory = [];
  constructor(private router: Router) {
    // nothing to do
  }
  public startHistory() {
    this.router.events
      .pipe(filter(e => e instanceof NavigationEnd))
      .subscribe(newUrl => this.routeHistory = [...this.routeHistory, newUrl]);
  }
  public getRouteHistory() {
    return this.routeHistory;
  }
}

在您的应用程序组件中:

constructor(private routerState: RouterState) {
  this.routerState.startHistory();
}

在您需要获取历史记录的组件中:

constructor(private routerState: RouterState) {}
yourFunction() {
  const allRoutes = this.routerState.getRouteHistory();
  const lastUrl = !!allRoutes.length 
    ?  allRoutes.slice(-2)
    :  '';
}

最新更新