conditional operator that compares values in router events

As I examine an object,

links = {
    link1: 'page1',
    link2: 'page2',
    link3: 'page3',
    link4: 'page4',
    link5: 'page5',
    link6: 'page6'
  }

I possess a function for retrieving the page URL through the router

Within this function, I make use of Object.keys to loop through the object values. If any value matches, it should assign other variables accordingly.

Although I aim to utilize a ternary statement, its functionality perplexes me at present. Can anyone shed some light on this matter?

A regular if statement does produce the desired outcome...

 private fetchPages(): void {
    this.subscriptions = this.router.events
      .pipe(
          filter((event) => event instanceof NavigationEnd)
      )
      .subscribe((event) => {

       let position: number;
       let located: boolean;

       Object.keys(this.links).map((key, i) => {

          if (this.links[key] === event['url']){
 // This is effective
            located = true;
              more details....
          }

// The following approach falls short
   event['url'] === this.links[key] ? (located = true, position = i) : (located = false, position = 0)

            });

         });
      }

Answer №1

Both code snippets are distinct

  • In a traditional if statement, you assign the value of found to true when the condition is met, without an accompanying else statement. This implies that once it's set to true, it remains true until the end of the loop, with no mechanism to set it to false
  • However, in a ternary operator, during each iteration, you either set the value of found to true or false, resulting in the final value being determined by the last item in the loop

Hence, these two codes possess differing logic To align the logic and outcome of the ternary operation with that of the simple if statement, including an else statement setting found = false will bring them in line (although this may not yield your anticipated result)

If you aim to replicate the logic of your basic if statement using a ternary approach, utilize the following syntax:

 event['url'] === this.progressUrls[key] ? (found = true, index = i) : (index = 0);

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

Managing large objects in Angular (type safety and more)

When using http, I receive an array of large objects with many values, some of which are irrelevant to me. The object (represented as ...) looks like this: id: '45678', attributes: { title: 'This is a title!' ... }, resources: [ ...

Is there a way to update the data on a view in Angular 9 without the need to manually refresh the page?

Currently, I am storing information in the SessionStorage and attempting to display it in my view. However, there seems to be a timing issue where the HTML rendering happens faster than the asynchronous storage saving process. To better illustrate this com ...

Is there a way to make the Sweetalert2 alert appear just one time?

Here's my question - can sweetalert2 be set to only appear once per page? So that it remembers if it has already shown the alert. Swal.fire({ title: 'Do you want to save the changes?', showDenyButton: true, showCancelButton: true, ...

Tips for converting API data to DTO (Data Transfer Object) using TypeScript

Here is an array of vehicles with their details. export const fetchDataFromApi = () => { return [ { vehicleId: 1, vehicleType: 'car', seats: 4, wheelType: 'summer', updatedAt: new Date().toISOString }, { vehicleId: 2, vehic ...

Troubleshooting Angular2 Testing Issue: Unhandled Promise Rejection: Error Encountered with Template Parsing - Unable to Bind to 'message' as Property is Unknown

Having an issue with two interconnected components. The first component is called: "GamePanelComponent" and it contains HTML file with a tag called: "my-game-panel-output" The second component looks like this: import { Component, Input } from '@ang ...

What is the best way to assign an HTML string to the DOM and connect it with an object?

In my angular HTML component template, I have the following markup: <div *ngIf="htmlTemplate && jsonObj" [innerHTML]="htmlTemplate"></div> The jsonObj variable is retrieved from an endpoint and looks like this: { fi ...

Having Trouble with Imported JavaScript File in Astro

Why isn't the js file working in Astro when I try to import or add a source in the Astro file? For example: <script src="../scripts/local.js"></script> or <script>import '../scripts/local.js'</script> I am ...

Why is it necessary to create a model in Angular?

Although I am relatively new to Angular and my understanding of all its concepts is limited, I am curious about the practical use of models in observables. For example, consider this code segment: getRestaurants = (): Observable<Restaurant[]> => ...

Delete an essential attribute from an entity

I am trying to remove a required property called hash from an object, but I keep encountering TypeScript or ESLint errors. All the properties of the interface are mandatory, and I do not want to make all properties optional using Partial. Here is the inte ...

Contrasting `Function` with `(...args: any[]) => any`

Can you explain the difference between Function and (...args: any[]) => any? I recently discovered that Function cannot be assigned to (...args: any[]) => any. Why is that so puzzling? declare let foo: Function; declare let bar: (...args: an ...

The module 'Express' does not have a public member named 'SessionData' available for export

I am encountering an issue while working on my TypeScript project. I am not sure where the error is originating from, especially since nothing has been changed since the last time I worked on it. node_modules/connect-mongo/src/types.d.ts:113:66 - error TS ...

What is the reason for the lack of variable assignment within the forEach method in Angular?

I am struggling with assigning a value to the variable "this.qdDias" and returning it. After using subscribe, I am unable to retrieve the value at the end of the method. Despite seeing the value in the console.log(this.qdDias), it becomes undefined when re ...

Utilizing Angular to import an SVG file from a backend and incorporate its content as a template

I am looking for a solution to load an SVG date from my Spring Boot backend and utilize it as an Angular template. Currently, the request is structured like this: getSVG (): Observable <any> { return this.http.get(`${environment.apiUrl}/path ...

"Utilizing Firebase Functions to update information in the Firebase Realtime Database on a daily basis

Currently, I am in the process of working on a project where I aim to provide users with a daily percentage of points based on their current available points and update this data in my Firebase database. My goal is to add points for users on a day-to-day b ...

Changing the global type in TypeScript

Currently, I am incorporating two third-party TypeScript libraries into my project. Interestingly, both of these libraries expose a global variable with the same name through the Window interface. However, they offer different methods for interacting with ...

Application built with Electron and Typescript encounters module-related crash

While working on developing a client using Electron with Typescript, I encountered the following error: The configuration in tsconfig.json looks like this: { "compilerOptions": { "target": "es5", "lib": [ ...

Managing a digital timepiece within a multiplayer gaming environment

I'm currently developing a fast-paced game where players control a block resembling a clock. To accurately calculate the time taken by each player to make moves, I store the start time of the game and record the timestamp of every move in the databas ...

Building React Typescript Components with Froala Editor Plugins

Attempting to integrate a custom plugin into a Froala Editor within my React application using the package react-froala-wysiwyg. Following a tutorial on incorporating a custom popup/plugin found here. Encountering an issue due to TypeScript incompatibility ...

The name 'console' could not be located

I am currently working with Angular2-Meteor and TypeScript within the Meteor framework version 1.3.2.4. When I utilize console.log('test'); on the server side, it functions as expected. However, I encountered a warning in my terminal: Cannot ...

Deleting an element in an Array of objects using Typescript

export class AppComponent implements OnInit { title = 'bucketList'; bucketList: BucketListItem[] = [ new BucketListItem( "Goa Trip", "Travel to Goa" ) ]; ngOnInit() { } onItemAdded(eventData) ...