Home > Net >  How to get previous route on 404 Error page in angular?
How to get previous route on 404 Error page in angular?

Time:07-05

I have some pages and when I change router link to some wrong url and it redirect me to 404 page. In this 404 Error page I have button that will redirect me to previous page. Now I have some problems that this redirect button when I click it redirects to that wrong url and again to 404.

I try to show by photo:

1)My route. write wrong url -> redirect to 404 page. Now the problem is when I click button to redirect at the previous route "Home" it redirect me to this wrong route.

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

CodePudding user response:

You can use JS history API to achieve this.

This is a sample to match your use case

goBack() {
    window.history.go(-2);
}

And this also keeps navigiation within the SPA scope (Page wouldn't refresh).

Side effect for this is that you need to make sure that the user follows a particular flow; in which he needs to be within a working page, then goes somewhere not found then get redirected to the 404 Page..

I would recommend a button that navigates to Home or Dashboard features instead.

CodePudding user response:

You can achieve this by number of ways , however I think the most elegant way is to use power of Injectable services in Angular.

Here is my solution of this problem:

  1. Create an Injectable service which will set a variable as soon as the current navigation end. The value of this variable can be used in any of the other components where ever we would need. Obviously one has to inject the service in the required component.

In my example, I have created RouterService:

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


@Injectable({ providedIn: 'root' })
export class RouterService {
  
  private previousUrl: string = undefined;
  private currentUrl: string = undefined;

  constructor(public 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;
  }    
}
  1. To illustrate the navigation , I have created two components viz. home and not-found Components.

Below are the code snippets for both of these components :

a) home.component.ts :

import { Component, VERSION } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';
import { RouterService } from '../../service/router.service';

@Component({
  selector: 'not-home-app',
  templateUrl: './home.component.html',
  styleUrls: [ './home.component.scss' ]
})
export class HomeComponent  {
  name = 'Angular '   VERSION.major;
  constructor(private router: Router,private routerService: RouterService) {}
  takeMeToNotFoundPage(){
    this.router.navigate(['/notFound']);
  }
}

b) not-found.component.ts:

import { Component, VERSION } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';
import { RouterService } from '../../service/router.service';

@Component({
  selector: 'not-found-app',
  templateUrl: './not-found.component.html',
  styleUrls: [ './not-found.component.scss' ]
})
export class NotFoundComponent  {
 
  
  previousUrl: string;
  constructor(private router: Router, private routerService: RouterService) {
    router.events
    .pipe(filter(event => event instanceof NavigationEnd))
    .subscribe((event: NavigationEnd) => {
      console.log('prev:', event.url);
      this.previousUrl = event.url;
    });
  }
  loadPreviousRoute(){
    let previous = this.routerService.getPreviousUrl();
    
    if(previous)
      this.routerService.router.navigateByUrl(previous);
  }
  
}

When the application will first load, I will route it to 'home' page. There I provided a button to navigate to not-found page. As you see in the above code of home component , I am setting the previous url in the router service which I can use in next component ( in this example it is 'not-found' component'

c) below are the html code snippets for both home and not-found components :

Home.component.html :

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

<button type="button" (click)="takeMeToNotFoundPage()">Not FOUND!</button>

not-found.component.html:

<p>
<span style="background-color: red">NOT FOUND!!</span>
</p>

<button type="button" (click)="loadPreviousRoute()">Go Back to Previous Route</button>

Hope this will help you to solve your problem. If it will , please provide your feedback and upvote it accordingly as it will help others in future too.

  • Related