首页 > 解决方案 > Angular:如何仅在应用程序内部返回

问题描述

在 Angular 中返回上一页非常简单

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

@Component({
  // component's declarations here
})
class SomeComponent {

  constructor(private _location: Location) 
  {}

  backClicked() {
    this._location.back();
  }
}

这相当于点击浏览器的“后退”按钮。但是如何修改此代码,以便将您带到应用程序外部this._location.back()的url ,而不是将您重定向到应用程序内部的路由。

例如,假设您在Google.com,然后您粘贴my-app.com/page-foo并以这种方式导航。this._location.back()将带您回到Google.com,但我希望它改为导航到my-app.com/page-bar

标签: angularangular2-routing

解决方案


在https://nils-mehlhorn.de/posts/angular-navigate-back-previous-page找到了答案。

1.制作一个新的navigation-service

import { Injectable } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { Location } from '@angular/common';

@Injectable({
  providedIn: 'root'
})
export class NavigationService {
  private MAX_HISTORY_LEN = 10; // prevent history from growing indefinitely
  private history: string[] = [];

  constructor(private router: Router, private location: Location) {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.history.push(event.urlAfterRedirects);
        if (this.history.length > this.MAX_HISTORY_LEN) {
          this.history.shift();
        }
      }
    });
  }

  back(): void {
    this.history.pop();
    if (this.history.length > 0) {
      this.location.back();
    } else {
      this.router.navigateByUrl('/');
    }
  }
}

2.将服务注入app.component.ts,以便跟踪整个应用程序的历史记录

export class AppComponent implements AfterViewInit {

  constructor(private navigationService: NavigationService) {
  }
  ...

3.(click)然后在您想使用它的任何地方更新功能。使用原始示例:

@Component({
  // component's declarations here
})
class SomeComponent {

  constructor(private navigationService: NavigationService) 
  {}

  backClicked() {
    this.navigationService.back();
  }
}

我从博文中做了一些调整:

  • 添加了一个MAX_HISTORY_LEN以防止历史数组在整个应用程序使用过程中无限增长
  • 注入navigation-serviceinapp.component.ts以便它始终跟踪历史记录。如果您只在调用的组件中注入服务,.back()那么在您第一次调用它时它可能没有历史记录。

推荐阅读