Validation of route parameters in Angular 4

Currently, I have a predefined route that includes a parameter called userID.

{
    path: "edit/:userID",
    component: EditUserComponent,
    canActivate: [AuthGuard]
  },

Within the edit-user-component.ts file, the following logic is implemented:

    this.requestID = this.route.snapshot.params.requestID;
        this.formService
          .getPendingRequest(this.requestID)
          .subscribe((form: any) => {
            form.forEach(element => {
              if (element) {
                this.editRequest.patchValue({
                  userID: element.userID,
                  userName:element.username,               
});
              } else {
                this.router.navigate(["view"]);
              }

As a result, unique ID's are assigned to every user. For example, I can access localhost:4200/edit/12. However, if I attempt to visit localhost:4200/edit/13 for a userID that does not exist in the MongoDB, I would like the page to automatically redirect to a 404 error page or the main homepage.

Answer №1

Understanding the concept should already be familiar to you:

  1. The approach involves utilizing the canActivate method in combination with AuthGuard. To achieve this, implement another route guard in a comparable manner and ensure the Router object is injected in the constructor(). By doing so, you can obtain the route parameters and use them to verify the existence of the data.
  2. Alternatively, utilize the Angular resolver. If the data is not present at the specified id, redirect from that point and return a rejected promise to halt the ongoing navigation process.

Answer №2

If the ID returns a 404 error, you can redirect to that specific page.

By utilizing the formService to retrieve the pending request based on the given request ID, we can handle the response accordingly:

this.formService.getPendingRequest(this.requestID).subscribe(form => {
    // code logic to handle the response
}, error => {
    if (error['status'] === 404) {
        this.router.navigate(['/home']);
    }
});

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

Error: The specified attribute "property" is not valid for the type "IntrinsicAttributes"

I am currently new to the world of React with Typescript and I am trying to learn how to create a Bar chart using Chart.js within a React Typescript App. My goal is to pass the value of the property datasets as a prop to the BarChart.tsx component. Below ...

Oops! An issue occurred: Attempting to access 'handle' property of an undefined value

Within my application, I've developed two distinct components: the Selector Component and the Shifter Component. The Selector Component is responsible for selecting a list of items that require updating, and it triggers a method in the Shifter Compone ...

Shuffle and Place indented list

I have a bunch of ideas and a list of projects. I need to choose one idea and match it with a project. I followed this guide to implement the drag and drop feature, but encountered an issue where every project gets assigned the same idea when dragging and ...

Having difficulty mastering the redux-form component typing

I am facing an issue while trying to export my component A by utilizing redux-form for accessing the form-state, which is primarily populated by another component. During the export process, I encountered this typing error: TS2322 Type A is not assignabl ...

It is not possible to transform Next.js into a Progressive Web App (P

Can someone assist me with PWA implementation? I tried running npm run build, but it was unsuccessful. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdbaacbface0abbfa2a3b98dfde3fce3fd">[email protected]</a> ...

The argument passed cannot be assigned to the parameter required

Currently, I am in the process of transitioning an existing React project from JavaScript to TypeScript. One function in particular that I am working on is shown below: const isSad = async (value: string) => { return await fetch(process.env.REACT_AP ...

What is the best way to assign the value of "this" to a variable within a component using Angular 2 and TypeScript?

In my component, I have the following setup: constructor() { this.something = "Hello"; } document.addEventListener('click', doSomething()); function doSomething(e) { console.log(this.something) // this is undefined } I am struggling to a ...

Arranging Objects by Alphabetical Order in Typescript

I am struggling with sorting a list of objects by a string property. The property values are in the format D1, D2 ... D10 ... DXX, always starting with a D followed by a number. However, when I attempt to sort the array using the following code snippet, it ...

An error occurred while defining props due to a parsing issue with the prop type. The unexpected token was encountered. Perhaps you meant to use `{`}` or `}`?

const dataProps = defineProps({ selectedData: <Record<string, string>> }); Under the closing bracket, there is a red line indicating: Error: Unexpected token. Consider using {'}'} or &rbrace; instead?eslint Expression expecte ...

Sending data between components in Angular can be achieved by using various methods. One common approach is to utilize

I am encountering an issue with a component named customers.component Below is the code from the customers.component.ts file: @Component({ selector: 'app-customer', templateUrl: './customer.component.html', styleUrls: ['./cu ...

Issue with loading React Router custom props array but custom string works fine

I am facing an issue with my ReactTS-App where I pass a prop via Router-Dom-Props to another component. The problem arises when I try to use meal.food along with meal.name, or just meal.food alone - it doesn't work as expected. Uncaught TypeError: mea ...

Activating external actions from the ngrx store through component interactions

I am working with a module that contains a modal where I perform some form tasks, and the modal has its own small feature store. After completing my work (specifically, when a save is successful), I need to trigger an output event in order for the parent ...

What could be causing the radio button to not be checked when the true condition is met in Angular?

I am working on an angular7 application that includes a dropdown list with radio buttons for each item. However, I am facing an issue where the radio button is not checked by default on successful conditions. Below is the code snippet from my component.htm ...

Issue with detecting errors in Angular unit test when using jest throwError method

Imagine I have a component that contains the following method: someMethod() { this.someService .doServicesMethod(this.id) .pipe( finalize(() => (this.loading = false)), catchError((e) => { this.showErrorMessage = true; ...

Filtering an array of objects based on another array of objects in Angular2 through the use of pipes

I'm having trouble understanding how to use the angular pipe to filter an array of objects based on another array of objects. Currently, I have a pipe that filters based on a single argument. I am working with two arrays, array1 and array2, both cont ...

What is the correct way to wrap an http.get in TypeScript?

My understanding of Typescript is limited, so I have a basic question related to my web application's frontend. In most http get-requests, I need to include two parameters. To simplify this process, I created a simple wrapper for HttpClient (from "ang ...

Displaying information in a table using Angular, instead of displaying it directly from

I'm currently developing an Angular application that utilizes ngx-datatable for displaying data. In this case, I have a Supplier object that needs to be shown in a table using ngx-datatable, with some columns displaying object properties and others sh ...

Is it possible to customize error messages in @hapi/joi?

Seeking assistance with custom error message overrides in Joi. Consider the schema outlined below. const joiSchema = Joi.object({ name: Joi.string().required(), email: Joi.string().email().required() }) try{ const schema = joiSchema.validateAsyn ...

Can someone show me how to implement RequestPromise in TypeScript?

I recently integrated the request-promise library into my TypeScript project, but I am facing some challenges in utilizing it effectively. When attempting to use it in the following manner: import {RequestPromise} from 'request-promise'; Reque ...

Angular Universal build stuck on rendering page while waiting for API response

I'm currently developing a compact web application using the angular universal starter in combination with pokeapi. To enhance performance and reduce API requests, I intend to implement pre-rendered pages since the data displayed remains mostly static ...