最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 5 - Which should I use to navigate backward - href or location.back()? - Stack Overflow

programmeradmin1浏览0评论

I have an app of which one can navigate to a page in which there is no way forwards. Think of clicking a program in a TV guide to open a page with that program's details, obviously you will want to go back to the TV guide.

For a button to go backward to the TV guide, I have an <a> tag.

Which would be the most advisable use case for this:

  1. Using href="/guide"

or

  1. Using (click)=goBack() where the function calls location.back()

I have an app of which one can navigate to a page in which there is no way forwards. Think of clicking a program in a TV guide to open a page with that program's details, obviously you will want to go back to the TV guide.

For a button to go backward to the TV guide, I have an <a> tag.

Which would be the most advisable use case for this:

  1. Using href="/guide"

or

  1. Using (click)=goBack() where the function calls location.back()
Share Improve this question asked Aug 23, 2018 at 10:56 physicsboyphysicsboy 6,37822 gold badges77 silver badges139 bronze badges 4
  • I would use the "back" method from the location service imported with: import {Location} from '@angular/mon'; – Geku Commented Aug 23, 2018 at 10:59
  • you can get answer from this link stackoverflow./questions/35446955/how-to-go-back-last-page/… – mittal bhatt Commented Aug 23, 2018 at 11:00
  • 1 Possible duplicate of How to go back last page – NullPointer Commented Aug 23, 2018 at 11:03
  • Consider if the user reaches the page by another way. If they click a Google search result that goes directly to the program details page, should the back button take them to the guide page, or back to their Google search results? – Joe Daley Commented Nov 2, 2019 at 6:46
Add a ment  | 

2 Answers 2

Reset to default 3

You should use built-in Location service of Angular as.

Angular-Location

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


@Component({
   selector: 'app-root',
   templateUrl: './app.ponent.html',
   styleUrls: ['./app.ponent.scss']
})

class AppComponent {
    constructor(private location: Location) {
    }
    back() {
        this.location.back();
    }
}

If you want to navigate in an Angular app, you don't want to use classic href links since they are designed to work for server-rendered apps, but not client-side apps that use the History Javascript API.

Prefer using the RouterLink from Angular.

Between RouterLink and location.back() the choice is yours, it depends whether you want to control the page you want to redirect to, or just want the same behavior as the back button from your browser.

发布评论

评论列表(0)

  1. 暂无评论