What are the steps to display a fallback route with TypeScript in Angular 6?

I am currently working with the AppRouting module and have the following code:

...
const routes: Routes = [
  ...
  {
    path: 'events',
    data: { preload: true },
    loadChildren: './events/events.module#EventsModule'
  },
  ...
  {
    path: '**',
    component: PageNotFoundComponent
  }
];
...

This configuration loads the Events module, which then loads the EventsRouting module:

...
const routes: Routes = [
  ...
  {
    path: ':id',
    component: EventsComponent,
  },
  {
    path: '',
    component: EventsListComponent
  }
  ...
];
...

Within the constructor of EventsComponent, I make an http.get call to the backend of the website:

constructor(...) {

  route.paramMap.subscribe(params => {
  let eventId = params.get("id");
  http.get<EventDTObject>(baseUrl + "api/v1/Events/Get/" + eventId).subscribe(result => {

      if (result==null) router.navigate(['/404']);
      this.eventDTObject = result;

    }, error => console.error(error));
  });
}

Most aspects of this setup function as intended, except for one issue with the line

if (result==null) router.navigate(['/404']);

Upon encountering a null result, the user is redirected to the PageNotFoundComponent. However, this redirection prevents users from utilizing the browser's back button effectively. Each attempt to navigate back leads to another 404 error due to the repeated http.get request.

I am contemplating a solution where instead of redirecting to "/404", it would be possible to display the fallback route "**" in the root routing module using TypeScript. This approach mirrors how accessing an unspecified route in the AppRouting module directs users to the component linked with the fallback route "**".

An ideal scenario might involve a structure like:

http.get<...>(...).subscribe(result => {
  if (result==null) router.showDefaultRoute();
  ...
}

Is this concept feasible?

(please consider the nested routing situation)

Answer №1

To navigate back in your application, you can utilize the Location Service and the "Back" function. In older versions of Angular 2, import the Location Service from "angular2/router", while in newer versions, use "@angular/common". Below is an example for implementing a back button in a form:

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


@Component({ directives: [ROUTER_DIRECTIVES] })
@RouteConfig([
    {...},
])
class AppComponent {
    constructor(private _location: Location) {
    }
    backClicked() {
        this._location.back();
    }
}

If you need to handle the back button being clicked on a web browser, you can make use of PlatformLocation and define an event listener for onPopState.

this.location.onPopState(()=>{
  this.location.back();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging $sceDelegateProvider for allowing Youtube in Typescript

I'm currently facing an issue with my app where I am trying to enable users to input Youtube URLs for videos to be displayed on the site. However, before implementing this feature, I need to whitelist Youtube. How can I adjust my typescript file (app. ...

Map does not provide zero padding for strings, whereas forEach does

Currently working on developing crypto tools, I encountered an issue while attempting to utilize the map function to reduce characters into a string. Strangely enough, one function works perfectly fine, while the other fails to 0 pad the string. What could ...

Tips for configuring the Index column within an Angular Mat-table (when the dataIndex displays 'NaN')

My Mat-Table is working perfectly, but I am looking for a way to add an auto-increment index. Below is the HTML code: <div class="mat-elevation-z8"> <table mat-table [dataSource]="dataSource" matSort> <ng-container matColumnDef="no"> ...

The function is failing to return the expected value received from the observable subscription

I am attempting to verify the existence of a user in an Angular's in-memory API by validating their username. The function checkUsernameExists(username) is supposed to return an Observable<boolean> based on whether the API responds with undefine ...

Nested REST API calls in Angular are causing only the inner call to be returned

When retrieving a ShoppingCart with ShoppingCartItems through an outer REST call, an Observable of the ShoppingCartItems is then used to make an inner call in order to enhance the items with a Provider. After the inner call, a tap(console.log) shows that ...

In the angular mat-chip-grid component, pressing the key combination of right Shift key and the letter M (<) on the keyboard functions as the Enter key

I have a code snippet that resembles this: https://material.angular.io/components/chips/overview ( Chips connected to an input field) <mat-form-field class="example-chip-list"> <mat-label>Favorite Fruits</mat-label> <mat ...

What could be causing the problem between typescript and Prisma ORM as I attempt to locate a distinct item?

I'm encountering a problem with using the prisma .findUnique() function. Even though my code doesn't display any compilation errors, attempting to access a product page triggers a runtime error. PrismaClientValidationError: Invalid `prisma.produ ...

The browser is not displaying the HTML correctly for the Polymer Paper-Menu component

I attempted to implement a paper-menu, but I am facing issues with the rendered HTML and its interaction. When I click on a menu item, the entire list disappears due to the paper-item elements not being properly placed inside a key div within the paper-men ...

Setting up the Font Awesome Pro version in Angular using the Font-Awesome package

The process of installing the pro version of Angular Font-awesome began with setting up my registry using these commands: npm config set "@fortawesome:registry" https://npm.fontawesome.com/ && \ npm config set "//npm.fontawesome.com/:_authTo ...

Is it possible to utilize pinia getter as the initial parameter in Vue3's watch function?

Issue Recap In Vue3, can Pinia getters be utilized as a watch target's first argument? System Details Vue version: 3.2.13 Pinia version: 2.1.4 TypeScript version: 4.5.5 Problem Description An error was encountered when attempting to reference the ...

An easy method to define argument types for every function type in TypeScript

How can I assign argument types to each function type in TypeScript? Each function has a parameter associated with it. [Example] type F1 = (arg: number) => void; type F2 = (arg: string) => void; const caller = (f: F1 | F2) => (n: number | strin ...

Utilizing RouterLink along with a button and conditional rendering in Angular

One issue I am facing is using *ngIf to navigate to a different page based on a variable. Despite having valid links, when I click on the button nothing happens. Here is the code snippet: <button mat-button > <span class=&quo ...

Having trouble with debugging in Chrome ever since upgrading to Angular 11?

Following the update of my angular 9.1 application to angular 11: While debugging within one of the libraries, Chrome no longer stops at my breakpoints. I am still able to debug other libraries and the app as usual. Within the troubl ...

What is the process for running an Angular 1.4 application on a system with Angular 6 installed?

After installing Angular 6 with CLI, I realized that my project was written in Angular 1.4. How do I go about running it? ...

Approach to retrieve the initial non-null object without relying heavily on conditional statements

In my Typescript code, I have two objects named Employee1 and Employee2. I am looking for a method that can return the non-null object between the two. If Employee1 is not null, return Employee1. If it's not null, return Employee2. If both are null, ...

Having difficulty casting the parameter type from Array.find() in TypeScript

In my codebase, I am dealing with the OrganisationInterface type: export declare interface OrganisationInterface { documents?: { [documentType: OrganisationDocumentTypesList]: { // enum id: string; name: string; ...

Typedoc Error: Attempted to assign a value to an undefined option (mode)

After installing typedoc with the command npm install typedoc --save-dev, I proceeded to add typedocOptions to tsconfig.json: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", // ...some lin ...

Angular: utilizing two instances of the <router-outlet> within a single component

Disclaimer: Despite finding a similar question on Stack Overflow with an accepted answer that did not solve my issue, I am still facing a problem. The challenge I am encountering is needing to use the same "router-outlet" twice in my main component. Howev ...

Creating web components with lit-element, leveraging rollup, postcss, and the tailwind framework for packaging

I have been attempting to package a functional web component that was developed using the lit-element/lit-html with the tailwind framework utilizing the postcss plugin from the rollup packager. Upon conducting a rollup, I discovered the compiled js and ht ...

typescript locate within the union type in the mapping expression

Consider the following: type X = { label: 'Xlabel', X_id: 12 }; type Y = { label: 'Ylabel', Y_id: 24 }; type Z = { label: 'Zlabel', Z_id: 36 }; type CharSet = X | Y | Z; I am looking for type CharSetByLabel = Map<CharSet& ...