如何返回最后一页

在Angular 2中有没有聪明的方法返回到最后一页?

类似的

this._router.navigate(LASTPAGE);

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

  • A页-> C页,点击返回A页。

  • B页-> C页,点击它,回到B页。

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

519848 次浏览

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

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

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

this._router.navigateByUrl(prevInstruction.urlPath);

实际上,你可以利用内置的位置服务,它拥有一个“返回”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';行很重要。

从beta 18开始:

# EYZ0

RC4:

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

在Angular 2的最终版本中。X / 4。这是文档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
}
}

我这样做的方式,而导航到不同的页面添加一个查询参数通过传递当前位置

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

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

在angular 4中使用preserveQueryParams,例如:

url: /list?page=1


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

当单击链接时,您将被重定向到edit/10?page=1,并保留参数

裁判:# EYZ0

也为我工作时,我需要移动回文件系统。 @angular: "^5.0.0"

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

我做了一个按钮,我可以在我的应用程序的任何地方重复使用。

创建这个组件

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

用Angular 5.2.9测试过

如果你使用锚而不是按钮,你必须将它设置为被动的链接href="javascript:void(0)",以使Angular Location工作。

# EYZ0

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()...' );
}
}

# EYZ0

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

另一个解决方案

# EYZ0

# EYZ0

你可以把它放到一个指令中,这个指令可以附加到任何可点击的元素上:

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>

在这些精彩的答案之后,我希望我的答案能找到一些人,并帮助他们。我编写了一个小服务来跟踪路线历史。开始了。

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;
}
}
要返回而不刷新页面,我们可以像下面这样在html中做 javascript: history.back() < / >强

<a class="btn btn-danger" href="javascript:history.back()">Go Back</a>

是的,你能做到。在你的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();
}
}

也许你想检查之前的历史点是否在你的应用程序中。例如,如果你直接进入你的应用程序并执行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()出现的地方),但由于应用程序返回历史,而不是按下一个新位置,用户将返回更远,可能会感到困惑。

我是这么说的:

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

此外,您还可以在历史记录为空的情况下使用此服务与回退功能

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 =“. . / LASTPAGE"

< p > 2022
利用你的应用程序路由-更多的是“角度方法”;而不是访问浏览器的位置对象来获取导航历史。 想想为什么你需要用户返回,以及“返回”在你的应用程序及其路由的更广泛的上下文中意味着什么

例如,从子路由返回到父路由

  this.router.navigate(['..'], {relativeTo: this.route});

你也可以阅读之前的导航

previousNavigation:先前成功的导航对象。只有 一个先前的导航是可用的,因此这个先前的

我想出了这个,你也可以检查是否有上一页。 确保在你的appComponent中使用该服务

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


interface HistoryData {
previousPage: string | null,
currentPage: string | null,
}


@Injectable({ providedIn: 'root' })
export class GoBackService {


private historyData: HistoryData = { previousPage: null, currentPage: null };


constructor(private router: Router, private location: Location) {
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.historyData.previousPage = this.historyData.currentPage;
this.historyData.currentPage = event.urlAfterRedirects;
}
});
}


public goBack(): void {
if (this.historyData.previousPage) this.location.back();
}


public canGoBack(): boolean {
return Boolean(this.historyData.previousPage);
}


}

只需使用< a href = " https://angular。io / api /共同/位置#回noreferrer“rel = >位置< / >,一个Angular服务,应用程序可以使用它与浏览器的URL进行交互。

导入:

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

注射:

constructor(private location: Location) { }

简单地使用它:

goBack() {
this.location.back(); // Navigates back in the platform's history
}

检测到的未更改组件的@Parziphal答案版本:

  constructor(private readonly router: Router, private readonly location: Location) {
location.onUrlChange(() => this.canGoBack = !!this.router.getCurrentNavigation()?.previousNavigation);
}


goBack(): void {
if (this.canGoBack) {
this.location.back();
}
}