How to get the previous page URL in angular 5

随声附和 提交于 2020-01-24 11:16:12

问题


I'm working with Angular 5 app and I need to know how to get the last URL to place it as a link to my back button. I found this location.back() but what I need the last url as a string. How could I get the string that generates location.back()?

Many Thanks!


回答1:


Angular 6 updated code for getting previous url as string.

import { Component, OnInit } from '@angular/core';
import { Router, RoutesRecognized } from '@angular/router';
import { filter, pairwise } from 'rxjs/operators';


export class AppComponent implements OnInit {

    constructor (
        public router: Router
    ) {
    }

    ngOnInit() {
        this.router.events
            .pipe(filter((e: any) => e instanceof RoutesRecognized),
                pairwise()
            ).subscribe((e: any) => {
                console.log(e[0].urlAfterRedirects); // previous url
            });
    }



回答2:


In the browser environment, location.back() is wrapper around the window.history object (for a partial path through the source, see here, here, here and here).

The contents within the History object are purposefully not accessible.

From the HTML History interface documention:

The actual entries are not accessible from script.

From MDN the window.history object documentation:

For security reasons the History object doesn't allow the non-privileged code to access the URLs of other pages in the session history, but it does allow it to navigate the session history.


As to an alternate approach, this answer provides a technique for listening for the last 2 NavigationEnd events.



来源:https://stackoverflow.com/questions/50883803/how-to-get-the-previous-page-url-in-angular-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!