如何回到最后一页

问题描述 投票:243回答:13

有没有一种聪明的方法可以回到Angular 2的最后一页?

就像是

this._router.navigate(LASTPAGE);

例如,页面C有一个返回按钮,

  • 页面A - >页面C,单击它,返回页面A.
  • 页面B - >页面C,单击它,返回到页面B.

路由器有这个历史信息吗?

angular angular2-routing
13个回答
468
投票

实际上,您可以利用内置的位置服务,该服务拥有“后退”API。

这里(在TypeScript中):

import {Component} from '@angular/core';
import {Location} from '@angular/common';

@Component({
  // component's declarations here
})
class SomeComponent {

  constructor(private _location: Location) 
  {}

  backClicked() {
    this._location.back();
  }
}

4
投票

在所有这些令人敬畏的答案之后,我希望我的答案找到了某人并帮助他们。我写了一个小服务来跟踪路线历史。在这里。

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

@Injectable()
export class RouteInterceptorService {
  private _previousUrl: string;
  private _currentUrl: string;
  private _routeHistory: string[];

  constructor(router: Router) {
    this._routeHistory = [];
    router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe((event: NavigationEnd) => {
        this._setURLs(event);
      });
  }

  private _setURLs(event: NavigationEnd): void {
    const tempUrl = this._currentUrl;
    this._previousUrl = tempUrl;
    this._currentUrl = event.urlAfterRedirects;
    this._routeHistory.push(event.urlAfterRedirects);
  }

  get previousUrl(): string {
    return this._previousUrl;
  }

  get currentUrl(): string {
    return this._currentUrl;
  }

  get routeHistory(): string[] {
    return this._routeHistory;
  }
}

2
投票

在角度4使用preserveQueryParams,例如:

url: /list?page=1

<a [routerLink]="['edit',id]" [preserveQueryParams]="true"></a>

单击该链接时,您将被重定向edit/10?page=1,保留params

ref:https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array


1
投票

从beta 18开始:

import {Location} from 'angular2/platform/common';


0
投票

另一种方法

window.history.back();


84
投票

在Angular 2.x / 4.x的最终版本中 - 这是文档https://angular.io/api/common/Location

/* typescript */

import { Location } from '@angular/common';
// import stuff here

@Component({
// declare component here
})
export class MyComponent {

  // inject location into component constructor
  constructor(private location: Location) { }

  cancel() {
    this.location.back(); // <-- go back to previous location on cancel
  }
}

19
投票

Tested with Angular 5.2.9

如果您使用锚点而不是按钮,则必须使用href="javascript:void(0)"作为被动链接以使Angular Location工作。

app.component.ts

import { Component } from '@angular/core';
import { Location } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {

  constructor( private location: Location ) { 
  }

  goBack() {
    // window.history.back();
    this.location.back();

    console.log( 'goBack()...' );
  }
}

app.component.html

<!-- anchor must be a passive link -->
<a href="javascript:void(0)" (click)="goBack()">
  <-Back
</a>

18
投票

您可以在路由类上实现routerOnActivate()方法,它将提供有关以前路由的信息。

routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) : any

然后你可以使用router.navigateByUrl()并传递从ComponentInstruction生成的数据。例如:

this._router.navigateByUrl(prevInstruction.urlPath);

11
投票

我制作了一个按钮,我可以在我的应用程序的任

创建此组件

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

@Component({
    selector: 'back-button',
    template: `<button mat-button (click)="goBack()" [color]="color">Back</button>`,
})
export class BackButtonComponent {
    @Input()color: string;

  constructor(private location: Location) { }

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

然后在需要后退按钮时将其添加到任何模板。

<back-button color="primary"></back-button>

注意:这是使用Angular Material,如果您不使用该库,则删除mat-buttoncolor


11
投票

<button backButton>BACK</button>

您可以将它放入一个可以附加到任何可点击元素的指令中:

import { Directive, HostListener } from '@angular/core';
import { Location } from '@angular/common';

@Directive({
    selector: '[backButton]'
})
export class BackButtonDirective {
    constructor(private location: Location) { }

    @HostListener('click')
    onClick() {
        this.location.back();
    }
}

用法:

<button backButton>BACK</button>

9
投票

当我需要像文件系统一样向后移动时,也适合我。附: @angular:“^ 5.0.0”

<button type="button" class="btn btn-primary" routerLink="../">Back</button>

7
投票

在RC4中:

import {Location} from '@angular/common';

6
投票

我在导航到不同页面时的方式通过传递当前位置添加查询参数

this.router.navigate(["user/edit"], { queryParams: { returnUrl: this.router.url }

在组件中阅读此查询参数

this.router.queryParams.subscribe((params) => {
    this.returnUrl = params.returnUrl;
});

如果存在returnUrl,则启用后退按钮,并在用户单击后退按钮时启用

this.router.navigateByUrl(this.returnUrl); // Hint taken from Sasxa

这应该能够导航到上一页。而不是使用location.back我觉得上面的方法更安全考虑用户直接登陆你的页面的情况,如果他用location.back按下后退按钮,它会将用户重定向到不是你的网页的上一页。

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