Angular 角度:如何仅在应用程序内部返回

Angular 角度:如何仅在应用程序内部返回,angular,angular2-routing,Angular,Angular2 Routing,返回到上一页是: 这相当于点击浏览器的“后退”按钮。但是,如何修改此代码,使得如果this.\u location.back()会将您带到应用程序外部的url,它会将您重定向到应用程序内部的路由 例如,假设您位于Google.com,然后粘贴到my app.com/page foo,并以该方式导航this.\u location.back()将带您返回Google.com,但我希望它导航到my app.com/page bar,在找到答案 1.创建新的导航服务: import { Injecta

返回到上一页是:

这相当于点击浏览器的“后退”按钮。但是,如何修改此代码,使得如果
this.\u location.back()
会将您带到应用程序外部的url,它会将您重定向到应用程序内部的路由

例如,假设您位于
Google.com
,然后粘贴到
my app.com/page foo
,并以该方式导航
this.\u location.back()
将带您返回
Google.com
,但我希望它导航到
my app.com/page bar
,在找到答案

1.创建新的
导航服务

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。然后在需要使用该功能的任何位置更新
(单击)
功能。使用原始示例:

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

  constructor(private navigationService: NavigationService) 
  {}

  backClicked() {
    this.navigationService.back();
  }
}
我在博客上做了一些调整:

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

根据,在您的情况下,您应该使用router.navigate方法这有返回的方法吗?您必须提供应该进行导航的url。通常这个url是已知的,如果它不是通用的解决方案,并且您在某个用户的actionRight组件中调用它,但是我想要的主要操作是返回
。使用
location.back()。如果我想像你说的那样使用
router.navigate
,我需要知道前面的url是什么
@Component({
  // component's declarations here
})
class SomeComponent {

  constructor(private navigationService: NavigationService) 
  {}

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