Exploring the usage of Booleans within an Angular component

Recently, I decided to delve into Angular and experiment with some hands-on projects. One of the challenges I encountered was utilizing the same component for both editing and creating a product. To address this, I implemented an if statement within the component to differentiate between the two actions. However, I noticed that the code inside the if statement wasn't being executed when the request URL was

http://localhost:4200/product/Edit/Redmond?edit=true
. Although I had included code to manage the route parameters (which I omitted for conciseness), I couldn't determine what exactly was missing from my implementation.

export class ProductEditComponent implements OnInit {
isEdit= false;
uiProduct:ProductModel;
ngOnInit() {
this.activatedRoute.queryParams.subscribe(queryParams=>{
  this.isEdit=queryParams['edit']      
  console.log(this.isEdit); // it's true here for the Edit Route
})
if (this.isEdit ==true) {      
  this.productService.
    GetProductByName(this.name)
    .subscribe((response: ProductModel) => {
      this.uiProduct = response;          
    });
}
}

Answer №1

When using this.activatedRoute.queryParams.subscribe
, keep in mind that it is asynchronous. Therefore, your isEdit variable will only receive a value after you have checked it. Consider moving the check inside the subscribe method or using await with the subscribe call.

Answer №2

After asynchronously assigning the isEdit variable, consider using RxJS higher order mapping operators (such as switchMap) for interdependent observables. You can also use the filter operator to emit only when the edit parameter is true.

Here's an example:

export class ProductEditComponent implements OnInit {
  uiProduct: ProductModel;

  ngOnInit() {
    this.activatedRoute.queryParams.pipe(
      filter((queryParams: any) => (!!queryParams['edit'])), // <-- proceed only if `edit` is true
      switchMap(_ => this.productService.GetProductByName(this.name))
    ).subscribe({
      next: (response: ProductModel) => {
        this.uiProduct = response;
      },
      error: (error: any) => {
        // handle error
      }
    });
  }
}

Update: Incorporate async query param elsewhere

To maintain the asynchronous nature of data and reuse it in other parts of your code, consider using RxJS ReplaySubject with a buffer of 1. Remember to close all open subscriptions when the component is destroyed, which can be achieved using takeUntil.

import { ReplaySubject, Subject } from 'rxjs';
import { tap, filter, switchMap, takeUntil } from 'rxjs/operators;

export class ProductEditComponent implements OnInit, OnDestroy {
  uiProduct: ProductModel;
  editSrc = new ReplaySubject<any>(1);
  edit$ = this.editSrc.asObservable();
  closed$ = new Subject<any>();

  // Implementation continues...

Answer №3

One of my favorite techniques is creating 2 separate routers for the same component:

 const routes: Routes = [
      { path: 'edit/:id', component: RequestReportComponent },
      { path: 'add', component: RequestReportComponent },
     ];

Within the component, I implement a check like this:

isEditMode:boolean;
  constructor(private route: ActivatedRoute) {
             this.isEditMode = this.route.snapshot.params.id;
   
  }

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

Having trouble getting the Angular 2 subscribe feature to function properly?

I encountered an exception stating 'Cannot read property 'subscribe' of undefined', but I am unable to figure out what mistake I have made. checkUserCredentials() { let response; let user = {email: this.email, password: this.pa ...

What is the Best Method for Dividing an Array in Typescript?

I'm working on a project using Angular2, and I have a collection of parties. const PARTIES: Party[] = [ { id: 1, title: "Main Event", description: "The biggest, most extravagant event in the last 10,000,000 years." }, { id: 2, title: "Secondary E ...

How can I apply styling to Angular 2 component selector tags?

As I explore various Angular 2 frameworks, particularly Angular Material 2 and Ionic 2, I've noticed a difference in their component stylings. Some components have CSS directly applied to the tags, while others use classes for styling. For instance, w ...

Checking the validity of an HTML tag with the contenteditable attribute set to true

Take for instance the input tag, which includes a field known as type. When type is set to "numeric", only numbers can be entered. Now, if I set a td element as contenteditable, is there a way to restrict the user from inputting anything other than number ...

Unable to set a breakpoint within Angular constructor or OnInit method

I am currently facing an issue with my Angular application where breakpoints set in F12 tools in Chrome or IE are not working. I have a simple test case below: export class LoginComponent implements OnInit { message: string; constructor(private r ...

Unable to successfully navigate Angular route when passing 2 parameters

This is my routing file: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomepageComponent } from './app/homepage/homepage.component'; import { SearchpageComponent } ...

Creating an additional attribute for a specific object type without needing to use any runtime code

type FormerActionsCustom = | { type: "ACTION_1" payload: string } | { type: "ACTION_2" payload: number } type CustomConverter = ... type UpdatedActions = CustomConverter<FormerActionsCustom, "group", "SECTION"> ...

Recording the details of an Angular project through the utilization of Compodoc

I am currently in the process of documenting my Angular + Typescript application using Compodoc. To install Compodoc, I utilized npm and executed the following command: 'npm install -g compodoc'. And included "compodoc": "./node_modules/ ...

What causes NG-REPEAT to malfunction when used with a JSON variable retrieved from a service?

I am trying to create a select dropdown menu in my Angular application by populating it with options from a JSON variable located in my StudentService.ts file. Within my service: careers : {}; constructor(private http: HttpClient) { this.selecte ...

Embracing Interfaces Over 'any' Types in TypeScript

https://i.stack.imgur.com/W6NMa.pngWould it be beneficial to utilize an interface as a variable type rather than opting for any? For instance, if I have 3 functions where I am declaring variables that can contain alphanumeric data, would defining them us ...

Using Typescript with Vue.js: Defining string array type for @Prop

How can I properly set the type attribute of the @Prop decorator to be Array<string>? Is it feasible? I can only seem to set it as Array without including string as shown below: <script lang="ts"> import { Component, Prop, Vue } from ...

Calling a Cloud Function directly with AngularFireFunction

I am currently facing an issue with integrating cloud functions as ExpressJS in my Angular website. While the cloud functions work perfectly fine when accessed directly at http://localhost:5001/project_id/us-central1/app, they seem to not function properly ...

The challenges of handling dynamic controls and reactive forms in Angular when editing, and ways to effectively update their values

I am currently working on creating an inline dynamic form using reactive forms. I have successfully added a new object and looped it in the DOM, but when I press the edit button, it doesn't work and produces errors in the console. Inside the object, t ...

Retrieving data using ngxs selector for displaying nested JSON data

My issue is related to the user object that contains nested arrays, making it difficult to access secondary arrays. I have created selectors with ngxs to retrieve and utilize data in HTML code, but extracting secondary arrays seems impossible. { "us ...

Tips for converting a Heic image file to a Jpeg or Png format within an Angular application in order to utilize ngx-image-cropper

Query - I am facing an issue with ngx-image-cropper where it does not support Heic image files as input for the '[imageChangedEvent]'. How can I convert a Heic image file to Jpeg or Png in Angular/typescript? Just so you know, when trying to loa ...

Ionic Angular encountered an unexpected 'ERROR' without any detailed explanation or logging

https://i.sstatic.net/aJPD1.png Hey there, I'm encountering some issues with my Ionic App. Currently, I am executing ionic cordova run android --livereload --consolelogs --serverlogs using a physical device. Although I can see console.logs, there ...

Guidance on extracting values from an array based on the latest month in Angular

I have a list of data: var dataList = [{ "date": "2022-09-08T04:00:00.000Z", "value": "1.70", }, { "date": "2022-08-24T04:00:00.000Z", "value": "1.20", }, { "date": "2022-08-02T04:00:00.000Z", "value": "0.03", }, { ...

Navigate after receiving data from an HTTP request in Angular

Whenever the user enters the 2FA code, I attempt to redirect them by sending a request to my API Rest to validate the code. A Promise is returned upon this request - oddly enough, during the first call the value remains undefined even though the token was ...

The Codegen configuration is unable to load the custom schema loader

Setting up codegen for my React project has been a challenge. I have been using a customized schema loader to fetch the schema from my API endpoint, but I keep encountering errors. Failed to load schema from pulse-api: Failed to load custom loader: codegen ...

The object in the if block may be considered 'null' according to ts-plugin(2531)

I encountered some issues with the code snippet provided above. After examining the event.target, I believe that it should not be nullable within the if statement. const importDatabase = async (event: Event) => { if (event.target) { const file = ( ...