【发布时间】:2016-05-28 13:57:58
【问题描述】:
在 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'; 行很重要。
【讨论】:
Location 的官方 Angular2 API 文档声明:“注意:最好使用路由器服务来触发路由更改。仅当您需要交互或创建规范化时才使用位置路由之外的 URL。” @Sasxa's answer 显然显示了一种使用 Router 来执行此操作的方法。但是,Location 方法肯定更方便。有谁知道为什么Router 方法可能比Location 方法更正确?
在 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>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>
【讨论】:
如果您使用锚点而不是按钮,则必须使用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(); } }
您可以在路由类上实现routerOnActivate() 方法,它将提供有关先前路由的信息。
routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) : any
然后您可以使用router.navigateByUrl() 并传递从ComponentInstruction 生成的数据。例如:
this._router.navigateByUrl(prevInstruction.urlPath);
【讨论】:
routerOnActivate 有文档
在所有这些很棒的答案之后,我希望我的答案能找到某人并帮助他们。我写了一个小服务来跟踪路线历史。就这样吧。
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;
}
}
【讨论】:
当我需要像在文件系统中一样移回时,也可以为我工作。 附注@角:“^5.0.0”
<button type="button" class="btn btn-primary" routerLink="../">Back</button>
【讨论】:
cd -)与 up (cd ..) 混淆了。不过,知道这行得通还是很方便的。
我制作了一个按钮,可以在我的应用程序的任何地方重复使用。
创建这个组件
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。
【讨论】:
我在导航到不同页面时通过传递当前位置添加查询参数的方式
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,它会将用户重定向到上一个页面,而不是您的网页。
【讨论】:
在 RC4 中:
import {Location} from '@angular/common';
【讨论】:
也许您想检查上一个历史点是否在您的应用中。例如,如果您直接进入您的应用程序并执行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() 的位置),但由于应用程序返回历史记录而不是推送新位置,因此用户将再往前走,可能会感到困惑。【讨论】:
要在不刷新页面的情况下返回,我们可以像下面这样在 html 中执行 javascript:history.back()
<a class="btn btn-danger" href="javascript:history.back()">Go Back</a>
【讨论】:
Location 服务。 official API
自 Beta 18 以来:
import {Location} from 'angular2/platform/common';
【讨论】:
另一种解决方案
window.history.back();
【讨论】:
在 Angular 4 中使用 preserveQueryParams,例如:
url: /list?page=1
<a [routerLink]="['edit',id]" [preserveQueryParams]="true"></a>
单击链接时,您将被重定向edit/10?page=1,保留参数
参考:https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array
【讨论】:
我用这种方式:
import { Location } from '@angular/common'
import { Component, Input } from '@angular/core'
@Component({
selector: 'Back_page',
template: `<button (click)="onBack()">Back</button>`,
})
export class BackPageComponent {
constructor(private location: Location) { }
onBack() {
this.location.back();// <-- go back to previous location
}
}
【讨论】:
是的,你可以做到。在你的 typescript 组件上写下这段代码,尽情享受吧!
import { Location } from '@angular/common'
import { Component, Input } from '@angular/core'
@Component({
selector: 'return_page',
template: `<button mat-button (click)="onReturn()">Back</button>`,
})
export class ReturnPageComponent {
constructor(private location: Location) { }
onReturn() {
this.location.back();
}
}
【讨论】:
如果历史记录为空,您也可以将此服务与回退功能一起使用
url-back.service.ts
import { Injectable } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
const EMPTY_HISTORY_LENGTH = 2;
/**
* This service helps to Navigate back to the prev page, and if no prev page,
* will redirect to the fallback url.
*/
@Injectable()
export class UrlBackService {
constructor(private router: Router, private location: Location) {}
/**
* This method will back you to the previous page,
* if no previous page exists, will redirect you to the fallback url.
* @param href - url, if tryNativeFirst is provided, this is fallback url
* @param tryNativeFirst - try to go back natively using browser history state.
*/
back(href: string, tryNativeFirst: boolean = false) {
if (tryNativeFirst) {
if (history.length === EMPTY_HISTORY_LENGTH) {
this.router.navigate(UrlBackService.urlToArray(href));
} else {
this.location.back();
}
} else {
this.router.navigate(UrlBackService.urlToArray(href));
}
}
/**
* In case that router.navigate method tries to escape all '/' in the string,
* was decided to split string to array, and if URL starts or ends with slash - remove them, eg:
* /my/url will be split to ['', 'my', 'url'], so we need to remove empty spaces use filter function.
* @param href
* @private
*/
private static urlToArray(href: string) {
return href.split('/').filter((notEmpty) => notEmpty);
}
}
url-back.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { UrlBackService } from './url-back.service';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
import { RouterTestingModule } from '@angular/router/testing';
describe('UrlBackService', () => {
let service: UrlBackService;
let router: Router;
let location: Location;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
providers: [UrlBackService],
});
service = TestBed.inject(UrlBackService);
router = TestBed.inject(Router);
location = TestBed.inject(Location);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('no meter what history state is, it should be redirected to the /my/url', () => {
spyOn(router, 'navigate');
service.back('/my/url');
expect(router.navigate).toHaveBeenCalledWith(['my', 'url']);
});
it('in case history is empty push to /my/url', () => {
spyOn(router, 'navigate');
service.back('/my/url', true);
expect(router.navigate).toHaveBeenCalledWith(['my', 'url']);
});
it('in case history is NOT empty push to url1', () => {
spyOn(location, 'back');
window.history.pushState(null, '', 'url1');
service.back('/my/url', true);
expect(location.back).toHaveBeenCalled();
});
});
【讨论】:
如果您使用最新的 Angular/TypeScript,请确保明确导入
import { Location } from '@angular/common';
和
onCancel() {
this.location.back();
}
【讨论】:
试试 routerLink="../child"
【讨论】: