Angular 5 - Which should I use to navigate backwar

2019-07-23 17:16发布

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()

2条回答
Lonely孤独者°
2楼-- · 2019-07-23 17:53

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.

查看更多
forever°为你锁心
3楼-- · 2019-07-23 18:05

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();
    }
}
查看更多
登录 后发表回答