如何确定Angular中的上一页网址?

问题描述 投票:48回答:7

假设我当前在页面上,其中包含URL /user/:id。现在从这个页面我导航到下一页:id/posts

现在有办法,以便我可以检查以前的URL是什么,即/user/:id

以下是我的路线

export const routes: Routes = [
  { 
    path: 'user/:id', component: UserProfileComponent
  },
  {  
    path: ':id/posts', component: UserPostsComponet 
  }
];
angular angular2-routing
7个回答
43
投票

您可以订阅路线更改并存储当前事件,以便在下一次发生时使用它

previousUrl: string;
constructor(router: Router) {
  router.events
  .filter(event => event instanceof NavigationEnd)
  .subscribe(e => {
    console.log('prev:', this.previousUrl);
    this.previousUrl = e.url;
  });
}

另见How to detect a route change in Angular 2?


49
投票

也许所有其他答案都是针对角度2.X.

现在它不适用于角度5.X.我正在使用它。

只有NavigationEnd,你不能得到以前的网址。

因为路由器的工作方式是“NavigationStart”,“RoutesRecognized”,......,“NavigationEnd”。

你可以查看

    router.events.forEach((event) => {
  console.log(event);
});

但即使使用“NavigationStart”,您仍然无法获得以前的URL。

现在你需要成对使用。

import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/pairwise';

constructor(private router: Router) {
  this.router.events
    .filter(e => e instanceof RoutesRecognized)
    .pairwise()
    .subscribe((event: any[]) => {
      console.log(event[0].urlAfterRedirects);
    });
}

使用成对,您可以看到来自哪个URL。

“RoutesRecognized”是从原点到目标网址的变化步骤。

所以过滤它并从中获取以前的URL。

最后但并非最不重要的,

此代码放置父组件或更高(ex,app.component.ts)

因为此代码在完成路由后触发。


23
投票

创建可注射服务:

import { Injectable } from '@angular/core';
import { Router, RouterEvent, NavigationEnd } from '@angular/router';

 /** A router wrapper, adding extra functions. */
@Injectable()
export class RouterExtService {

  private previousUrl: string = undefined;
  private currentUrl: string = undefined;

  constructor(private router : Router) {
    this.currentUrl = this.router.url;
    router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {        
        this.previousUrl = this.currentUrl;
        this.currentUrl = event.url;
      };
    });
  }

  public getPreviousUrl(){
    return this.previousUrl;
  }    
}

然后在任何需要的地方使用它。要尽快存储当前变量,必须使用AppModule中的服务。

// AppModule
export class AppModule {
  constructor(private routerExtService: RouterExtService){}

  //...

}

// Using in SomeComponent
export class SomeComponent implements OnInit {

  constructor(private routerExtService: RouterExtService, private location: Location) { } 

  public back(): void {
    this.location.back();
  }

  //Strange name, but it makes sense. Behind the scenes, we are pushing to history the previous url
  public goToPrevious(): void {
    let previous = this.routerExtService.getPreviousUrl();

    if(previous)
      this.routerExtService.router.navigateByUrl(previous);
  }

  //...

}

12
投票

Angular 6更新了将前一个url作为字符串的代码。

import { Router, RoutesRecognized } from '@angular/router';
import { filter, pairwise } from 'rxjs/operators';


export class AppComponent implements OnInit {

    constructor (
        public router: Router
    ) {
    }

    ngOnInit() {
        this.router.events
            .pipe(filter((e: any) => e instanceof RoutesRecognized),
                pairwise()
            ).subscribe((e: any) => {
                console.log(e[0].urlAfterRedirects); // previous url
            });
    }

6
投票

这对角色6有用:

this.router.events
            .subscribe((event) => {
              if (event instanceof NavigationStart) {
                window.localStorage.setItem('previousUrl', this.router.url);
              }
            });

1
投票

@GünterZöchbauer也可以将它保存在localstorage但我不喜欢它)更好地保存在服务中并从那里获得这个价值

 constructor(
        private router: Router
      ) {
        this.router.events
          .subscribe((event) => {
            if (event instanceof NavigationEnd) {
              localStorage.setItem('previousUrl', event.url);
            }
          });
      }

-5
投票

当我想回到上一页时,我遇到了类似的问题。解决方案比我想象的要容易。

<button [routerLink]="['../']">
   Back
</button>

然后它返回到父URL。我希望它会帮助某人;)

© www.soinside.com 2019 - 2024. All rights reserved.