获取以前的路线Angular 7

Tes*_*dor 5 typescript angular angular7

我创建了一个小服务,可以在其中存储路线更改。

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;
  }    
}
Run Code Online (Sandbox Code Playgroud)

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

sid*_*hah 11

使用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();
  }   
}
Run Code Online (Sandbox Code Playgroud)

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

https://stackblitz.com/angular/qvvrbgrmmda

  • 为什么将此标记为正确答案?OP从未说过他想以编程方式返回。 (3认同)
  • 如果您没有历史记录,这将不起作用。例如,如果您在新选项卡中打开页面。 (3认同)

crg*_*g63 6

这是一种获取之前路线的方法@angular/router

在原始帖子中查找更多信息

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

};
Run Code Online (Sandbox Code Playgroud)


Vik*_*iya 5

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

 get previousRoute$(): Observable<string> {
    return this.router.events.pipe(
      filter(e => e instanceof RoutesRecognized),
      pairwise(),
      map((e: [RoutesRecognized, RoutesRecognized]) => e[0].url)
    );
  }
Run Code Online (Sandbox Code Playgroud)

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

this.previousRoute$.subscribe(url => {
  //perform your action
});
Run Code Online (Sandbox Code Playgroud)

注意:当用户处于第二次导航时,此 observable 将开始发出事件。

  • 您不应该使用 getter 来执行此操作,因为 Angular 可能会多次调用它并产生内存泄漏。您应该存储它并在组件销毁生命周期中取消订阅它 (2认同)
  • @VikashDahiya 这是正确的,但也许其他开发人员不会按照预期的方式使用它。@alexandre-rousseau 提出的论点非常重要,恕我直言。因此我只想为其声明一个字段。`私人订阅:订阅;previousRoute$: Observable&lt;string&gt; = this.router.events.pipe(...); ngOnInit() { this.subscription = this.previousRoute$.subscribe(...) }` (2认同)