Home > database >  Unable to consistently determine previous route
Unable to consistently determine previous route

Time:07-04

i am running into an issue where i am unable to determine the previous route / the page that called that component. I cant use the this.location.back() function as i need to pass some info back to the previous page, that's why i created the below service. It often works but many times it does not and claims the previous page is undefined. The issue seems to be often on the initial one when i start the app or reload browser, even then it should hit my URL service and know where i routed from which would be the home page.

My code for the service i am using looks like this

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

@Injectable()
export class PreviousRouteService {

  private previousUrl: string;
  private currentUrl: string;

  constructor(private router: Router) {
    this.currentUrl = this.router.url;


    this.router.events
      .pipe(filter((evt: any) => evt instanceof RoutesRecognized), pairwise())
      .subscribe((events: RoutesRecognized[]) => {

        this.previousUrl = events[0].urlAfterRedirects;
        console.log('previous url', this.previousUrl);
      });
  }

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

And i call the Routes like this

 this.router.navigateByUrl(`/Farm/FarmMaster/${data.DocId}`, {
                state,
        });

And then to go back i call this

   goBack() {
        console.log('Will Route back to : '   this.previousRouteService.getPreviousUrl())
        this.state$
            .pipe(
                takeWhile(_ => this.alive),
            )
            .subscribe(state => {
                console.log(state)
                this.router.navigate(['/' this.previousRouteService.getPreviousUrl()]);
            });
    }

CodePudding user response:

After some more research i found the issue for me, i had to make sure the PreviousRouteService was loaded in the app.module

export class AppModule {
    constructor(private previousRouteService : PreviousRouteService){}
    
}

Credit to @Juliano https://stackoverflow.com/a/48866813/9860237

  • Related