Dealing with situations where an Angular component's route lacks a resolver

I have a component that handles both creating new items and updating existing ones. I have set up a Resolver for the 'edit/:id' route, but have not used one for the 'new' route.

  ngOnInit() {
    if (!(this.route.snapshot.url[0].path === '/new')) {
      this.route.data
      .subscribe((data: { project: Project}) => {
        this.project= data.project;
      });
    }
  }

I have been able to retrieve two different URLs, one showing the full path and the other only displaying the last part of the path.

this.route.snapshot.url[0].path
// Result: 'new'

this.router.url
// Result: '/admin/projects/new'

I am exploring better ways to determine when to load resolver data and when not to. Is using the URL a good approach? If so, which URL variable would you recommend?

Answer №1

One way to differentiate between adding a new item or editing an existing one is by using route data.

Here's how you can implement it in your router:

{path: 'admin/projects/:id', component: YourComponent, data: {action: 'edit'}},

And in your component:

ngOnInit(): void {
    if (this.route.snapshot.data['action'] === 'edit') {
        this.route.data.subscribe((data: { project: Project}) => {
            this.project = data.project;
        });
    }
}

It's not necessarily better than using URLs for identification purposes, but it's another approach you can consider.

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

What is the best way to display just the selection outcome?

Currently, my code displays a full list of clinics. When I select a province in the dropdown menu, it only shows the clinics located in that specific province. I would like to modify this behavior so that the full list of clinics is not visible initially ...

The Angular application's navbar component is not receiving the necessary bootstrap classes

I am currently using Bootstrap 3.4.1 with AngularCLI 6.0.8, but I am facing an issue where none of the identified Bootstrap classes are showing up on my webpage when I run ng serve. Despite trying to update Bootstrap versions and experimenting with new cl ...

Issue with Primeng table: row grouping width does not work properly when scrollable is enabled

Currently, I am implementing a Primeng table within an Angular project. Below is the code snippet showcasing how the table is being utilized: <p-table [value]="cars" dataKey="brand" [scrollable]="'true'" scrollHeight="400px"> <ng-te ...

Using NestJS to pass request and response parameters

I have a function in my services set up like this: ` @Injectable() export class AppService { getVerifyToken(req: Request, res: Response) { try { let accessToken = process.env.ACCES_TOKEN_FB; let token = req.query["hub.verify_t ...

Experiencing problems with npm installation while trying to compile Angular2 source code

I am trying to compile angular2 source code on my Windows 8.1 x64 development machine. The versions of Node and Npm I have are as follows: Node version 5.1.0 Npm version 3.3.12 1) Successfully cloned the repository 2) Executed bower install command - S ...

Include module A in module B, even though module A has already included module B's Angular

Currently, I am facing an issue with circular dependencies between two modules - User and Product. The User Module has already imported the Product Module to utilize the ProductListComponent. Now, I need to import/use the UserListComponent from the User Mo ...

Modifying the Iterator Signature

My goal is to simplify handling two-dimensional arrays by creating a wrapper on the Array object. Although the code works, I encountered an issue with TypeScript complaining about the iterator signature not matching what Arrays should have. The desired fu ...

creating a new date instance with a specific time zone

Creating a Date object with a dynamically selected timezone is my current goal while I am located in the IST time zone. To avoid the unpredictable behavior of Date.parse(), I am looking for an alternative method. Let's say we set the tzOffset to +05:3 ...

Implementing various custom validators in Angular 2 reactive forms

I am facing an issue with two custom validator functions in a reactive form. I have the following function that creates the form within the component constructor: private createForm(): void { this.passwordUpdateForm = this.formBuilder.group({ newpassw ...

Angular's DomSanitizer not functioning properly with the Transform css property

I have a question regarding my use of DomSanitizer. The background css property seems to be working fine, but the transform property is not displaying any output. I'm unsure where I might be going wrong in my implementation. In my Angular 8 code: i ...

Are there any solutions to refresh a page by clicking a button in next.js?

I am currently learning how to work with next.js and I'm facing an issue where I need to reload my page to make a new API request. As a beginner, I'm not sure how to achieve this. I've tried a few methods but none of them seem to work. Below ...

What are the steps to implement the `serialport` library in `deno`?

After tinkering with Deno to extract readings from an Arduino, I encountered a roadblock when it came to using the serialport library correctly. Here is what I attempted: According to a post, packages from pika.dev should work. However, when trying to use ...

A guide to implementing unit tests for Angular directives with the Jest testing framework

I am currently integrating jest for unit testing in my Angular project and I am relatively new to using jest for unit tests. Below is the code snippet for DragDropDirective: @HostListener('dragenter',['$event']) @HostListener(& ...

Having trouble sending an email using nodejs and mailgun

Before accusing me of asking a duplicate question, I want to clarify that I have already searched for solutions and none of them worked for me. For example, I tried the solution provided in this link: Example of the domain name for mailgun before nodejs? ...

Delay the Ngrx effect by 2 seconds before initiating the redirect

I have an ngrx effect that involves calling an HTTP method and then waiting for 2 seconds before redirecting to another page. However, the current behavior is that it redirects immediately without waiting. confirmRegistration$ = createEffect(() => { ...

Implementing the ternary operator on a nested object field in typescript to enforce type validation

Is there an issue with my code or is this intentional? I want to write something similar to this. type MyDefinition = { salutation: string; value?: { typeOfValue: string; val?: string }; }; function create(name: string, input?: Partial<MyDefin ...

Tips for obtaining the "inner type" of a particular "instance" in TypeScript's generics

Unable to find more appropriate language to elaborate beyond the title, I'm going to rely on the code itself: let var1 = someExternalLibraryMethod(); // assume var1 is implicitly Promise<string> let var2: typeof var1; // this approach enables ...

The JSX component cannot use 'Router' as a valid element

Error Message The error message states that 'Router' cannot be used as a JSX component because its return type 'void' is not a valid JSX element. TS2786 import App from './App'; 5 | > 6 | ReactDOM.render(<Router ...

Issue with Readonly modifier not functioning as expected in Angular/Typescript

My goal is to create a component property that is read-only. However, I am facing an issue where the readonly modifier does not seem to have any effect. View example on stackblitz According to the documentation, once I initialize the cars property in the ...

Angular: extracting value from forkJoin nested within another observable's pipe

Here is the scenario that needs to be implemented: An API call is made which returns a response containing an array of objects. The objects are then mapped to another array of objects. For each item in this new array, another API call needs to be made. Th ...