在Angular中,有多种方法可以实现返回上一页。

  1. 使用 location.back()
    Location服务提供了back方法,该方法用于导航到浏览器历史记录的上一页。
import { Location } from '@angular/common';

// 在构造函数中注入 Location
constructor(private location: Location) {}

// 返回上一页
goBack() {
  this.location.back();
}
  1. 使用 Router 服务
    Router服务提供了多种导航方法,其中之一是navigateBack,可以用来返回上一页。
import { Router } from '@angular/router';

// 在构造函数中注入 Router
constructor(private router: Router) {}

// 返回上一页
goBack() {
  this.router.navigateBack(['/']);
}
  1. 使用 window.history
    你还可以直接使用window.history对象来返回上一页。
import { Component } from '@angular/core';

@Component({
  selector: 'app-example',
  template: `
    <button (click)="goBack()">Go Back</button>
  `,
})
export class ExampleComponent {
  // 返回上一页
  goBack() {
    window.history.back();
  }
}

选择其中一种方法,根据你的项目需求和代码结构来决定使用哪种方式。

12-02 06:55