[angular] Angular에서 이전 페이지 URL을 확인하는 방법은 무엇입니까?

현재 URL이있는 페이지에 있다고 가정합니다 /user/:id. 이제이 페이지에서 다음 페이지로 이동합니다 :id/posts.

이제 방법이 있습니까? 그러면 이전 URL이 무엇인지 확인할 수 있습니다 /user/:id.

아래는 내 경로입니다

export const routes: Routes = [
  {
    path: 'user/:id', component: UserProfileComponent
  },
  {
    path: ':id/posts', component: UserPostsComponet
  }
];



답변

경로 변경을 구독하고 현재 이벤트를 저장하여 다음에 발생할 때 사용할 수 있습니다.

previousUrl: string;
constructor(router: Router) {
  router.events
  .pipe(filter(event => event instanceof NavigationEnd))
  .subscribe((event: NavigationEnd) => {
    console.log('prev:', event.url);
    this.previousUrl = event.url;
  });
}

Angular에서 경로 변경을 감지하는 방법을 참조하십시오 .


답변

아마도 다른 모든 대답은 각도 2.X에 대한 것입니다.

이제 각도 5.X에서는 작동하지 않습니다. 나는 그것으로 일하고있다.

NavigationEnd 만 있으면 이전 URL을 가져올 수 없습니다.

라우터는 “NavigationStart”, “RoutesRecognized”, …, “NavigationEnd”에서 작동하기 때문입니다.

당신은 확인할 수 있습니다

    router.events.forEach((event) => {
  console.log(event);
});

그러나 여전히 “NavigationStart”를 사용해도 이전 URL을 가져올 수 없습니다.

이제 pairwise를 사용해야합니다.

import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/pairwise';

constructor(private router: Router) {
  this.router.events
    .filter(e => e instanceof RoutesRecognized)
    .pairwise()
    .subscribe((event: any[]) => {
      console.log(event[0].urlAfterRedirects);
    });
}

pairwise를 사용하면 어떤 URL이 시작되고 있는지 확인할 수 있습니다.

“RoutesRecognized”는 출발지에서 타겟 URL로 변경하는 단계입니다.

그래서 그것을 필터링하고 그것에서 이전 URL을 가져옵니다.

마지막으로,

이 코드를 상위 구성 요소 이상 (예 : app.component.ts)에 넣습니다.

이 코드는 라우팅을 마친 후에 실행되기 때문입니다.

각도 업데이트 6+

events.filter필터는 이벤트의 일부가 아니므로 코드를 변경 때문에 오류를 제공

import { filter, pairwise } from 'rxjs/operators';

this.router.events
.pipe(filter((evt: any) => evt instanceof RoutesRecognized), pairwise())
.subscribe((events: RoutesRecognized[]) => {
  console.log('previous url', events[0].urlAfterRedirects);
  console.log('current url', events[1].urlAfterRedirects);
});


답변

주입 가능한 서비스를 만듭니다.

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

 /** A router wrapper, adding extra functions. */
@Injectable()
export class RouterExtService {

  private previousUrl: string = undefined;
  private currentUrl: string = undefined;

  constructor(private router : Router) {
    this.currentUrl = this.router.url;
    router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        this.previousUrl = this.currentUrl;
        this.currentUrl = event.url;
      };
    });
  }

  public getPreviousUrl(){
    return this.previousUrl;
  }
}

그런 다음 필요한 모든 곳에서 사용하십시오. 현재 변수를 가능한 한 빨리 저장하려면 AppModule에서 서비스를 사용해야합니다.

// AppModule
export class AppModule {
  constructor(private routerExtService: RouterExtService){}

  //...

}

// Using in SomeComponent
export class SomeComponent implements OnInit {

  constructor(private routerExtService: RouterExtService, private location: Location) { }

  public back(): void {
    this.location.back();
  }

  //Strange name, but it makes sense. Behind the scenes, we are pushing to history the previous url
  public goToPrevious(): void {
    let previous = this.routerExtService.getPreviousUrl();

    if(previous)
      this.routerExtService.router.navigateByUrl(previous);
  }

  //...

}


답변

이전 URL을 문자열로 가져 오기위한 Angular 6 업데이트 코드.

import { Router, RoutesRecognized } from '@angular/router';
import { filter, pairwise } from 'rxjs/operators';


export class AppComponent implements OnInit {

    constructor (
        public router: Router
    ) {
    }

    ngOnInit() {
        this.router.events
            .pipe(filter((e: any) => e instanceof RoutesRecognized),
                pairwise()
            ).subscribe((e: any) => {
                console.log(e[0].urlAfterRedirects); // previous url
            });
    }


답변

이것은 각도> = 6.x 버전에서 나를 위해 일했습니다.

this.router.events
            .subscribe((event) => {
              if (event instanceof NavigationStart) {
                window.localStorage.setItem('previousUrl', this.router.url);
              }
            });


답변

내가 사용하고 각도 (8) 와 프랭클린 – 경건한을 해결해 @ 문제의 답을. 제 경우에는 구독 내에서 이전 URL을 가져 오면 뷰의 일부 데이터가 첨부되면 부작용이 발생합니다.

내가 사용한 해결 방법은 경로 탐색에서 이전 URL을 선택적 매개 변수로 보내는 것입니다.

this.router.navigate(['/my-previous-route', {previousUrl: 'my-current-route'}])

구성 요소에서이 값을 얻으려면 :

this.route.snapshot.paramMap.get('previousUrl')

this.router 및 this.route는 각 구성 요소의 생성자 내부에 삽입되고 @ angular / router 멤버로 가져옵니다.

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


답변

Angular 8 및 rxjs 6 (2019 버전)

다른 훌륭한 솔루션을 기반으로 솔루션을 공유하고 싶습니다.

먼저 경로 변경을 수신하는 서비스를 만들고 Behavior Subject에 마지막 이전 경로를 저장 한 다음 생성자의 주 app.component에이 서비스를 제공 한 다음이 서비스를 사용하여 원하는 때에 원하는 이전 경로를 가져옵니다.

사용 사례 : 사용자를 광고 페이지로 리디렉션 한 다음 사용자가 원래 있던 위치로 자동 리디렉션하므로 마지막 이전 경로가 필요합니다.

// service : route-events.service.ts

import { Injectable } from '@angular/core';
import { Router, RoutesRecognized } from '@angular/router';
import { BehaviorSubject } from 'rxjs';
import { filter, pairwise } from 'rxjs/operators';
import { Location } from '@angular/common';

@Injectable()
export class RouteEventsService {

    // save the previous route
  public previousRoutePath = new BehaviorSubject<string>('');

  constructor(
    private router: Router,
    private location: Location
  ) {

    // ..initial prvious route will be the current path for now
    this.previousRoutePath.next(this.location.path());


    // on every route change take the two events of two routes changed(using pairwise)
    // and save the old one in a behavious subject to access it in another component
    // we can use if another component like intro-advertise need the previous route
    // because he need to redirect the user to where he did came from.
    this.router.events.pipe(
      filter(e => e instanceof RoutesRecognized),
      pairwise(),
        )
    .subscribe((event: any[]) => {
        this.previousRoutePath.next(event[0].urlAfterRedirects);
    });

  }
}

app.module에서 서비스 제공

  providers: [
    ....
    RouteEventsService,
    ....
  ]

app.component에 삽입

  constructor(
    private routeEventsService: RouteEventsService
  )

마지막으로 원하는 구성 요소에서 저장된 이전 경로를 사용하십시오.

  onSkipHandler(){
    // navigate the user to where he did came from
    this.router.navigate([this.routeEventsService.previousRoutePath.value]);
  }