programing

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

nicescript 2023. 5. 22. 23:27
반응형

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

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

비슷한 것

this._router.navigate(LASTPAGE);

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

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

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

라우터에 이 기록 정보가 있습니까?

실제로 "Back" 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();
  }
}

편집: 언급된 바와 같이 by @charith.ar umapperuma.Location가 합야다에서 .@angular/common 그 래서그서import {Location} from '@angular/common';라인이 중요합니다.

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
  }
}

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

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>

은 수있다니습을 구현할 수 .routerOnActivate()경로 클래스의 메서드는 이전 경로에 대한 정보를 제공합니다.

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

그러면 사용할 수 있습니다.router.navigateByUrl() 생된데전달에서 합니다.ComponentInstruction예:

this._router.navigateByUrl(prevInstruction.urlPath);

이전 기록 지점이 앱 내에 있는지 확인하고 싶을 수도 있습니다.예를 들어, 당신이 앱에 직접 들어가서 하는 경우location.back()(()를 <- back예를 들어, 도구 모음의 단추)를 클릭하면 앱 내의 다른 곳으로 이동하는 대신 브라우저의 기본 페이지로 돌아갑니다.

확인 방법은 다음과 같습니다.

import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-foo',
  template: ''
})
export class FooComponent {

  private readonly canGoBack: boolean;

  constructor(
    private readonly route: ActivatedRoute,
    private readonly router: Router,
    private readonly location: Location
  ) {
    // This is where the check is done. Make sure to do this
    // here in the constructor, otherwise `getCurrentNavigation()`
    // will return null. 
    this.canGoBack = !!(this.router.getCurrentNavigation()?.previousNavigation);
  }

  goBack(): void {
    if (this.canGoBack) {
      // We can safely go back to the previous location as
      // we know it's within our app.
      this.location.back();
    } else {
      // There's no previous navigation.
      // Here we decide where to go. For example, let's say the
      // upper level is the index page, so we go up one level.
      this.router.navigate(['..'], {relativeTo: this.route});
    }
  }

}

현재 경로를 로드한 내비게이션에 이전 형제가 있는지 확인합니다.탐색 프로세스가 활성화된 상태에서 생성자에서 이 작업을 수행해야 합니다.

그러나 이는 주의 사항이 없는 것은 아닙니다.

  • canGoBack이전 위치가 실제로 앱 내에 있지만 페이지가 새로 고쳐진 경우에도 false가 됩니다.
  • 사용자는 이전 페이지로 "돌아가기"를 원할 수 있습니다(여기서goBack()브라우저의 뒤로 버튼을 클릭하면 발생하지만, 앱이 새 위치를 누르는 대신 기록으로 되돌아갔기 때문에 사용자는 더 멀리 돌아가서 혼란스러울 수 있습니다.

또한 파일 시스템에서와 같이 다시 이동해야 할 경우에도 작업을 수행합니다.추신 @angular: "^5.0.0"

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

이 모든 멋진 대답이 있은 후에, 저는 제 대답이 누군가를 찾아서 그들을 도와주기를 바랍니다.저는 경로 이력을 기록하기 위해 작은 서비스를 작성했습니다.자, 시작합니다.

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

저는 제 앱 어디서나 재사용할 수 있는 버튼을 만들었습니다.

이 구성 요소 만들기

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을 입니다. 않을 에는 ": "Angular Material"을 하십시오. 해당 라이브러리를 사용하지 않는 경우 다음을 제거합니다.mat-button그리고.color.

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

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을 사용하는 대신 위의 방법이 사용자가 직접 페이지에 착륙하는 경우를 고려하면 안전하다고 생각합니다. 그리고 그가 location.back과 함께 뒤로 버튼을 누르면 사용자가 웹 페이지가 아닌 이전 페이지로 리디렉션됩니다.

응용프로그램이 브라우저의 URL과 상호 작용하는 데 사용할 수 있는 Angular 서비스인 Location을 사용하면 됩니다.

가져오기:

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

주입:

constructor(private location: Location) { }

간단히 사용:

goBack() {
    this.location.back(); // Navigates back in the platform's history
}

RC4의 경우:

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

다른 해결책

window.history.back();

페이지를 새로 고치지 않고 돌아가려면 아래의 javascript:history.back()과 같이 html로 하면 됩니다.

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

최신 Angular/TypeScript를 사용하는 경우 명시적으로 가져오십시오.

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

그리고.

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

베타 18 이후:

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

에서는 각 4회 사 시 용 시를 합니다.preserveQueryParamsex:

url: /list?page=1

<a [routerLink]="['edit',id]" [preserveQueryParams]="true"></a>

링크를 클릭하면 리디렉션됩니다.edit/10?page=1

참조: https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array

나는 다음과 같은 방법을 사용합니다.

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

@Component({
    selector: 'Back_page',
    template: `<button  (click)="onBack()">Back</button>`,
})
export class BackPageComponent {
  constructor(private location: Location) { }

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

2022
탐색 기록을 위해 브라우저의 위치 개체에 액세스하는 대신 앱 라우팅을 "각도 접근 방식"으로 활용합니다.사용자가 '뒤로' 이동해야 하는 이유와 애플리케이션 및 해당 경로의 광범위한 맥락에서 '뒤로'가 무엇을 의미하는지 생각해 보십시오.

예: 하위 경로에서 상위 경로로 돌아가기

  this.router.navigate(['..'], {relativeTo: this.route});

이전 탐색에 대해서도 읽을 수 있습니다.

previousNavigation : 이전에 성공한 Navigation 개체입니다.하나의 이전 탐색만 사용할 수 있으므로 이 이전 탐색 개체에는 자체 이전 탐색에 대한 null 값이 있습니다.

제가 생각해 낸 건데, 이전 페이지가 있는지도 확인해보세요.appComponent에서 서비스를 사용해야 합니다.

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

interface HistoryData {
  previousPage: string | null,
  currentPage: string | null,
}

@Injectable({ providedIn: 'root' })
export class GoBackService {

  private historyData: HistoryData = { previousPage: null, currentPage: null };

  constructor(private router: Router, private location: Location) {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.historyData.previousPage = this.historyData.currentPage;
        this.historyData.currentPage = event.urlAfterRedirects;
      }
    });
  }

  public goBack(): void {
    if (this.historyData.previousPage) this.location.back();
  }

  public canGoBack(): boolean {
    return Boolean(this.historyData.previousPage);
  }

}

가져오기:

import { Location } from '@angular/common';
import { Router } from '@angular/router';

생성자:

constructor(private readonly router: Router, private readonly location: Location) {
  location.onUrlChange(() => this.canGoBack = !!this.router.getCurrentNavigation()?.previousNavigation);
}

선택적으로, 응용프로그램 외부로 돌아가지 않도록 합니다.

private canGoBack: boolean = false;

constructor(private router:Router,private location:Location){
  this.canGoBack = !!(this.router.getCurrentNavigation()?.previousNavigation);
}

뒤로 가기:

goBack(): void {
  if (this.canGoBack) {
    this.location.back();
  }
}

HTML:

<button (click)="goBack()"></button>

네, 당신은 할 수 있습니다. 이 코드를 당신의 타자기 구성요소에 쓰고 즐기세요!

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

@Component({
    selector: 'return_page',
    template: `<button mat-button (click)="onReturn()">Back</button>`,
})
export class ReturnPageComponent {
  constructor(private location: Location) { }

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

또한 기록이 비어 있는 경우 이 서비스를 폴백 기능과 함께 사용할 수 있습니다.

url-back.service.ts

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

import { Router } from '@angular/router';

const EMPTY_HISTORY_LENGTH = 2;

/**
 * This service helps to Navigate back to the prev page, and if no prev page,
 * will redirect to the fallback url.
 */
@Injectable()
export class UrlBackService {
  constructor(private router: Router, private location: Location) {}

  /**
   * This method will back you to the previous page,
   * if no previous page exists, will redirect you to the fallback url.
   * @param href - url, if tryNativeFirst is provided, this is fallback url
   * @param tryNativeFirst - try to go back natively using browser history state.
   */
  back(href: string, tryNativeFirst: boolean = false) {
    if (tryNativeFirst) {
      if (history.length === EMPTY_HISTORY_LENGTH) {
        this.router.navigate(UrlBackService.urlToArray(href));
      } else {
        this.location.back();
      }
    } else {
      this.router.navigate(UrlBackService.urlToArray(href));
    }
  }

  /**
   * In case that router.navigate method tries to escape all '/' in the string,
   * was decided to split string to array, and if URL starts or ends with slash - remove them, eg:
   * /my/url will be split to ['', 'my', 'url'], so we need to remove empty spaces use filter function.
   * @param href
   * @private
   */
  private static urlToArray(href: string) {
    return href.split('/').filter((notEmpty) => notEmpty);
  }
}

url-back.service.spec.ts

import { TestBed } from '@angular/core/testing';

import { UrlBackService } from './url-back.service';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
import { RouterTestingModule } from '@angular/router/testing';

describe('UrlBackService', () => {
  let service: UrlBackService;
  let router: Router;
  let location: Location;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      providers: [UrlBackService],
    });
    service = TestBed.inject(UrlBackService);
    router = TestBed.inject(Router);
    location = TestBed.inject(Location);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('no meter what history state is, it should be redirected to the /my/url', () => {
    spyOn(router, 'navigate');
    service.back('/my/url');
    expect(router.navigate).toHaveBeenCalledWith(['my', 'url']);
  });

  it('in case history is empty push to /my/url', () => {
    spyOn(router, 'navigate');
    service.back('/my/url', true);
    expect(router.navigate).toHaveBeenCalledWith(['my', 'url']);
  });

  it('in case history is NOT empty push to url1', () => {
    spyOn(location, 'back');
    window.history.pushState(null, '', 'url1');

    service.back('/my/url', true);
    expect(location.back).toHaveBeenCalled();
  });
});

routerLink="../마지막 페이지"

탐지된 구성 요소 변경 안 함에 대한 @Parziphal 응답 버전:

  import { Location } from '@angular/common';
  import { Router } from '@angular/router';

  constructor(private readonly router: Router, private readonly location: Location) {
    location.onUrlChange(() => this.canGoBack = !!this.router.getCurrentNavigation()?.previousNavigation);
  }

  goBack(): void {
    if (this.canGoBack) {
      this.location.back();
    }
  }

Angular 14의 최신 업데이트입니다.previousUrl이 정의되지 않은 경우 미리 정의된 이전 URL로 라우팅됩니다.

import { Location } from '@angular/common';
import { filter, Subject, takeUntil } from 'rxjs';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';

private previousUrl: string;
private ngUnsubscribe: Subject<any> = new Subject<any>();

constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private location: Location
) {
    router.events
        .pipe(
            takeUntil(this.ngUnsubscribe),
            filter((event) => event instanceof NavigationEnd)
        )
        .subscribe((event: NavigationEnd) => {
            this.previousUrl = event.url;
        });
}

public async goBack() : Promise<void> {
   if (this.previousUrl) {
     this.location.back();
   } else {
     await this.router.navigate(['..'], {
         relativeTo: this.activatedRoute,
     });
   }
}

ngOnDestroy(): void {
    this.ngUnsubscribe.next(true);
    this.ngUnsubscribe.complete();
}

언급URL : https://stackoverflow.com/questions/35446955/how-to-go-back-last-page

반응형