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

不打扰是莪最后的温柔 提交于 2020-01-04 04:28:50

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/51984177/angular-5-which-should-i-use-to-navigate-backward-href-or-location-back

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