在Angular 2中,有没有一种聪明的方法返回上一页?
类似于
this._router.navigate(LASTPAGE);
例如,页面C有一个返回按钮,
从页面A跳转到页面C,点击按钮,返回页面A。
从页面B跳转到页面C,点击按钮,返回页面B。
在Angular 2中,有没有一种聪明的方法返回上一页?
类似于
this._router.navigate(LASTPAGE);
例如,页面C有一个返回按钮,
从页面A跳转到页面C,点击按钮,返回页面A。
从页面B跳转到页面C,点击按钮,返回页面B。
实际上,您可以利用内置的位置服务,它拥有一个"后退"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();
}
}
编辑:正如@charith.arumapperuma所提到的,Location
应该从 @angular/common
导入,因此 import {Location} from '@angular/common';
这一行很重要。
在 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
}
}
<button backButton>返回</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>
如果您使用锚点而不是按钮,您必须将其设置为被动链接,并使用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>
javascript:void(0)
。类似这样... `@Directive({ selector: '[clickPreventDefault]' })export class ClickPreventDefaultDirective {
@HostListener("click", ["$event"]) onClick($event: Event) {
$event.preventDefault();
}
}` - bmd也许您想检查一下历史记录的上一个点是否在您的应用程序内。例如,如果您直接进入您的应用程序并执行location.back()
(例如通过工具栏中的<- back
按钮),您将回到浏览器的主页,而不是去往您的应用程序中的其他地方。这是我检查这个问题的方法:
import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
@Component({
selector: 'app-foo',
template: ''
})
export class FooComponent {
private readonly canGoBack: boolean;
constructor(
private readonly route: ActivatedRoute,
private readonly router: Router,
private readonly location: Location
) {
// This is where the check is done. Make sure to do this
// here in the constructor, otherwise `getCurrentNavigation()`
// will return null.
this.canGoBack = !!(this.router.getCurrentNavigation()?.previousNavigation);
}
goBack(): void {
if (this.canGoBack) {
// We can safely go back to the previous location as
// we know it's within our app.
this.location.back();
} else {
// There's no previous navigation.
// Here we decide where to go. For example, let's say the
// upper level is the index page, so we go up one level.
this.router.navigate(['..'], {relativeTo: this.route});
}
}
}
我们检查加载当前路由的导航是否有前一个同级元素。这必须在构造函数中完成,而导航过程仍在活动状态。
但是,这样做并不是没有注意事项:
canGoBack
将为false,即使前一个位置实际上在我们的应用程序内,但页面已刷新。goBack()
发生的位置),但由于应用程序回退历史记录而不是推送新位置,因此用户将会更加困惑。您可以在路由类上实现routerOnActivate()
方法,它会提供有关先前路由的信息。
routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) : any
然后您可以使用router.navigateByUrl()
并传递从 ComponentInstruction
生成的数据。例如:
this._router.navigateByUrl(prevInstruction.urlPath);
routerOnActivate
有文档说明。 - Bojan Kogoj在所有这些精彩的答案之后,我希望我的答案能找到某个人并帮助他们解决问题。我编写了一个小服务来跟踪路由历史记录。以下是它。
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;
}
}
当我需要在文件系统中后退时,这也对我有用。 P.S. @angular: "^5.0.0"
<button type="button" class="btn btn-primary" routerLink="../">Back</button>
cd -
)和“上一级”(cd ..
)搞混了。不过,知道这个也很方便。 - devios1我创建了一个按钮,可以在我的应用程序中重复使用。
创建这个组件
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-button
和color
。
注:若您未使用 Angular Material 库,则需删除 mat-button
和 color
。
只需使用 Location ,一个 Angular 服务,应用程序可以使用它与浏览器的 URL 进行交互。
导入它:
import { Location } from '@angular/common';
constructor(private location: Location) { }
简单使用它:
goBack() {
this.location.back(); // Navigates back in the platform's history
}
Router
方法实现此功能的方式。但是,使用Location
方法肯定更方便。有人知道为什么Router
方法可能比Location
方法更正确吗? - Andrew Willems