获取上一条路线 Angular 7

Get previous route Angular 7

我创建了一个可以存储路线更改的小服务。

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

@Injectable()
export class RouteState {

  private previousUrl: string;
  private currentUrl: string;

  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;
  }    
}

但是每次路由更改时,变量 currentUrl 和 previousUrl 都是未定义的。我做错了什么吗?

使用 angular 的位置服务,它内置于 angular 并从“@angular/common”导入它,如下所示:

import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';

import { Hero }         from '../hero';
import { HeroService }  from '../hero.service';

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: [ './hero-detail.component.css' ]
})
export class HeroDetailComponent implements OnInit {
  @Input() hero: Hero;

  constructor(
    private location: Location
  ) {}

  goBack() {
    this.location.back();
  }   
}

然后使用location.back()转到上一页。这是一个工作示例:

https://stackblitz.com/angular/qvvrbgrmmda

如果您不想使用Angular提供的定位服务,那么您可以尝试以下服务。

// service to get prev route
@Injectable()
export class RouteBackService {
    public getPreviousUrl(routeArray): string {
        let prevRoute = '';
        for (let i = 0; i < routeArray.length - 1; i++) {
            if (routeArray[i].url._value[0].length > 0) {
                prevRoute += routeArray[i].url._value[0].path + '/';
            } 
        }
        return prevRoute.slice(0, -1);
    }
}

// in the component from where you want to route back    
export class YourComponent {
    constructor (private _aRoute: ActivatedRoute,
                   private _routeBack: RouteBackService
                   private _router: Router) {}
    goBack() {
        const prevRoute=this._routeBack.getPreviousUrl(this._aRoute.pathFromRoot);
        this._router.navigate([prevRoute]);
    }
}

如果你只想要以前的路线,你可以像这样创建一个可观察的

 public previousRoute$: Observable<string> = this.router.events.pipe(
   filter((e) => e instanceof RoutesRecognized),
   pairwise(),
   map((e: [RoutesRecognized, RoutesRecognized]) => e[0].url)
 );

现在您可以订阅这个 observable 并执行任何操作(确保您在 OnDestroy 事件上取消订阅这个 observable。)

this.previousRoute$.subscribe(url => {
  //perform your action
});

注意:当用户进行第二次导航时,此可观察对象将开始发出事件。

这是使用 @angular/router

获取先前路线的方法

the original post

上查找更多信息
import { Injectable } from '@angular/core';
import { Router, RouterEvent, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';

@Injectable({
    providedIn: "root"
})
export class PreviousRouteService {

    private previousUrl: string;
    private currentUrl: string;

    constructor(private router: Router) {

        this.currentUrl = this.router.url;
        this.previousUrl = null;

        this.router.events
                    .pipe(filter((event: RouterEvent) => event instanceof NavigationEnd))
                    .subscribe((event: NavigationEnd) => {
                        this.previousUrl = this.currentUrl;
                        this.currentUrl = event.urlAfterRedirects;
                        console.log("prev: ", this.previousUrl)
                        console.log("curr: ", this.currentUrl)
                    });

    }

    public getPreviousUrl() {
        return this.previousUrl;
    }

};