简体   繁体   中英

Angular 5 - Which should I use to navigate backward - href or 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()

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

Angular-Location

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


@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM