마지막 페이지로 돌아가는 방법


366

Angular 2의 마지막 페이지로 돌아가는 현명한 방법이 있습니까?

같은 것

this._router.navigate(LASTPAGE);

예를 들어 C 페이지에는 Go Back버튼이 있습니다.

  • 페이지 A-> 페이지 C, 클릭하여 페이지 A로 돌아갑니다.

  • 페이지 B-> 페이지 C, 클릭하여 페이지 B로 돌아갑니다.

라우터에 이력 정보가 ​​있습니까?

답변:


669

실제로 "뒤로"API를 소유 한 내장 위치 서비스를 활용할 수 있습니다.

여기 (TypeScript에서) :

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

편집 :로는 charith.arumapperuma이 @ 언급 Location에서 수입해야 @angular/common소위 import {Location} from '@angular/common';라인이 중요하다.


75
위치는 Angular 2의 이전 릴리스에서 "angular2 / router"에서 가져와야합니다. 최신 릴리스에서는 "@ angular / common"에서 가져와야합니다.
— charith.arumapperuma

2
프레임 워크에 내장되어 있다면 "native" "window.history.back ();"을 사용해야 할 이유가 없습니다. 이것은 HTML5 기능입니다 ( developer.mozilla.org/en-US/docs/Web/API/Window/history )
— Amir Sasson

7
유용한 Angular2 API 문서의 Location상태는 "참고 : 라우터 서비스를 사용하여 경로 변경을 트리거하는 것이 좋습니다. 라우팅 외부에서 정규화 된 URL과 상호 작용하거나 만들어야하는 경우에만 위치를 사용하십시오." @Sasxa의 대답 은 분명히 Router이것을 수행 하는 데 사용하는 방법을 보여줍니다 . 그러나이 Location방법은 확실히 더 편리합니다. 왜 Router방법이 Location방법 보다 더 정확한지 알고 있습니까?
— Andrew Willems

2
@Andrew : this.location.back ()을 사용하면 두 번 돌아갈 수 없다는 문제가 발생했습니다. 초기 사이트로 돌아갑니다.
— Johannes

1
@ yt61, 확실하지 않으면 재사용 가능성이 있습니까? 또는 다양한 경로에서 지정된 페이지로 이동할 수 있다면 경로를 미리 알 수 없습니다.
— Amir Sasson

111

Angular 2.x / 4.x 의 최종 버전 에서는 다음 문서가 있습니다. https://angular.io/api/common/Location

/* typescript */

import { Location } from '@angular/common';
// import stuff here

@Component({
// declare component here
})
export class MyComponent {

  // inject location into component constructor
  constructor(private location: Location) { }

  cancel() {
    this.location.back(); // <-- go back to previous location on cancel
  }
}

1
이전 화면으로 되돌아가는 동안 서비스중인 객체를 사용하지 않고도 입력 된 값을 유지할 수 있습니다.
— Vignesh

location.back ()이 실행되는 동안 애니메이션을 다시 표시하는 방법은 무엇입니까?
— 스노우베이스

48

<button backButton>BACK</button>

클릭 가능한 요소에 첨부 할 수있는 지시문에 이것을 넣을 수 있습니다.

import { Directive, HostListener } from '@angular/core';
import { Location } from '@angular/common';

@Directive({
    selector: '[backButton]'
})
export class BackButtonDirective {
    constructor(private location: Location) { }

    @HostListener('click')
    onClick() {
        this.location.back();
    }
}

용법:

<button backButton>BACK</button>

대단해!
— Rafael de Castro

1
이 페이지를 새로 고치고 "this.location.back ()"을 트리거하는 버튼을 클릭하면 페이지 새로 고침 만 트리거됩니다. 위치 모듈이 이전 경로가 존재하는지 감지 할 수있는 방법이 있습니까?
— Henry LowCZ

잘 했어! ;)
— elciospy

사용자가 뒤로 버튼이있는 페이지로 직접 이동 한 경우 버튼을 클릭하면 브라우저 (플랫폼) 기록에 따라 이전 페이지로 앱에서 제외됩니다.
— hastrb

미래의 독자들을 위해 API 문서를
— hastrb

23

Angular 5.2.9로 테스트

당신이 버튼을 대신 앵커를 사용하는 경우 당신은 그것을 확인해야 수동 링크 와 href="javascript:void(0)"각도 위치를 작동하게하는.

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {

  constructor( private location: Location ) { 
  }

  goBack() {
    // window.history.back();
    this.location.back();

    console.log( 'goBack()...' );
  }
}

app.component.html

<!-- anchor must be a passive link -->
<a href="javascript:void(0)" (click)="goBack()">
  <-Back
</a>

을 사용하는 대신 'clickPreventDefault'지시문을 만드는 것이 좋습니다 javascript:void(0). 뭔가처럼 ... @Directive({ selector: '[clickPreventDefault]' }) export class ClickPreventDefaultDirective { @HostListener("click", ["$event"]) onClick($event: Event) { $event.preventDefault(); } }
— BMD

@bmd 감사합니다.보다 정교한 방법이지만 작동합니다. 다른 작동 솔루션은 herf : <a (click)="goBack()">를 사용하지 않지만 HTML 유효성 검사기를 통과 시키지는 않습니다.
— JavierFuentes

20

routerOnActivate()경로 클래스에서 메소드를 구현할 수 있으며 이전 경로에 대한 정보를 제공합니다.

routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) : any

그런 다음 router.navigateByUrl()에서 생성 된 데이터를 사용 하고 전달할 수 있습니다 ComponentInstruction. 예를 들면 다음과 같습니다.

this._router.navigateByUrl(prevInstruction.urlPath);

이것은 Angular 2.1.0에도 유효합니까?
— smartmouse

1
문서가있다, 나는 그렇게 생각하지 않습니다 @smartmouserouterOnActivate
— 보얀 Kogoj

4
이 답변의 routerOnActivate () 링크가 손상되었습니다. 이것은 릴리스 버전에서 수행하는 방법이 아닌 것 같습니다.
— rmcsharry

14

파일 시스템에서와 같이 되돌려 야 할 때도 나를 위해 일하십시오. PS @ 각도 : "^ 5.0.0"

<button type="button" class="btn btn-primary" routerLink="../">Back</button>

7
나는 이것이 효과가 있기를 희망했지만 이것은 페이지로 이동하기 전에 있던 경로가 아닌 그 위에있는 다음 경로로 돌아갑니다. 이것이 존재한다는 것을 알고는 좋지만 구성 요소에 대한 진입 점이 여러 개인 경우이 방법은 원래 위치가 아닌 위의 경로로만 되돌아갑니다.
— Scott Byers

"파일 시스템에서와 같이 되돌려 야 할 때"라고 쓴 것처럼 :) 나에게도이 동작은 예상치 못한 것이었다.
— Shevtsiv Andriy

12

앱의 어느 곳에서나 재사용 할 수있는 버튼을 만들었습니다.

이 구성 요소 만들기

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

@Component({
    selector: 'back-button',
    template: `<button mat-button (click)="goBack()" [color]="color">Back</button>`,
})
export class BackButtonComponent {
    @Input()color: string;

  constructor(private location: Location) { }

  goBack() {
    this.location.back();
  }
}

그런 다음 뒤로 버튼이 필요할 때 템플릿에 추가하십시오.

<back-button color="primary"></back-button>

참고 : Angular Material을 사용하고 있습니다 . 해당 라이브러리를 사용하지 않는 경우 mat-buttonand 를 제거하십시오 color.


이 접근 방식은 명명 된 라우터 콘센트에서 작동합니까? 페이지에 여러 개가 있고 그중 하나만 다시 돌아가고 싶다고 가정 해보십시오.
— rrd

해당 상황에 대해 다른 접근 방식을 사용해야합니다. 두 개의 다른 라우터 콘센트에 동일한 뒤로 버튼이있는 경우 둘 다 동일한 작업을 수행하고 변경된 마지막 라우터 콘센트로 돌아갑니다.
— Todd Skelton

명명 된 아울렛의 경우이 접근 방식이 효과적이라는 것을 알았습니다. this.router.navigate ([ '../'], {relativeTo : this.route})
— rrd

다른 구성 요소 내에서이 구성 요소를 사용하는 방법은 무엇입니까?
— RN Kushwaha

12

이 멋진 답변을 모두 마치고 나서 내 답변이 누군가를 찾아서 도와 주길 바랍니다. 나는 경로 이력을 추적하기 위해 작은 서비스를 썼습니다. 여기 간다.

import { Injectable } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';

@Injectable()
export class RouteInterceptorService {
  private _previousUrl: string;
  private _currentUrl: string;
  private _routeHistory: string[];

  constructor(router: Router) {
    this._routeHistory = [];
    router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe((event: NavigationEnd) => {
        this._setURLs(event);
      });
  }

  private _setURLs(event: NavigationEnd): void {
    const tempUrl = this._currentUrl;
    this._previousUrl = tempUrl;
    this._currentUrl = event.urlAfterRedirects;
    this._routeHistory.push(event.urlAfterRedirects);
  }

  get previousUrl(): string {
    return this._previousUrl;
  }

  get currentUrl(): string {
    return this._currentUrl;
  }

  get routeHistory(): string[] {
    return this._routeHistory;
  }
}

거의 모든 솔루션을 시도한 후에이 방법이 더 일관된 방법이라는 것을 알았습니다
— .

특정 링크에서 페이지를 열고 페이지 트리의 페이지로 돌아가려면 어떻게해야합니까?
— Ivan

8

다른 페이지로 이동하는 동안 현재 위치를 전달하여 쿼리 매개 변수를 추가하는 방법

this.router.navigate(["user/edit"], { queryParams: { returnUrl: this.router.url }

컴포넌트에서이 쿼리 매개 변수를 읽으십시오.

this.router.queryParams.subscribe((params) => {
    this.returnUrl = params.returnUrl;
});

returnUrl이 있으면 뒤로 단추를 사용 가능하게하고 사용자가 뒤로 단추를 클릭하면

this.router.navigateByUrl(this.returnUrl); // Hint taken from Sasxa

이전 페이지로 이동할 수 있어야합니다. 위의 방법은 location.back을 사용하는 대신 사용자가 귀하의 페이지로 직접 방문하는 경우를 고려하여 더 안전하다고 생각합니다.


ActivatedRoute를 가져 와서 queryParams 구독 (예 : this.route.queryParams.subscribe)에서 라우터 대신 사용해야하지만 그렇지 않으면 작동하는 것 같습니다!
— Stephen Kaiser

나를 위해 그것은 각도 4에서도 라우터 자체와 잘 작동하고 있습니다
— Puneeth Rai

1
가장 좋은 답변이지만 Angular 5 (최대 x?)에서는 "ActivatedRoute"객체를 삽입하고이 객체에 queryParams를 사용해야합니다. Stephen Kaiser는 이미 언급했습니다.
— Satria


3

페이지를 새로 고치지 않고 돌아가려면 다음과 같이 html로 할 수 있습니다. javascript : history.back ()

<a class="btn btn-danger" href="javascript:history.back()">Go Back</a>

Location대신 서비스를 사용하는 것이 좋습니다 . 공식 API
— hastrb

2

베타 18 이후 :

import {Location} from 'angular2/platform/common';



2

다른 해결책

window.history.back();


나를 위해 작동 location.back ()도 작동하지만 --prod로 컴파일하지는 않습니다.
— Alex
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.