Displaying exclusively distinct values in the selection box/dropdown menu

My goal is to retrieve data from the SQL server database and populate the corresponding fields on the frontend. While I am able to fetch the data, some fields in the response contain duplicate values in the dropdown menu. Here is an example of how my Component looks:

export class ReportingFilterComponent implements OnInit {
 ShipmentList: ShipmentByProject[];
 output= [];
 entityUrl = 'ShipmentDetail/GetByReportingProject?repPrj=000634';

 constructor(service: DataService) {
 this.ShipmentList = [];
 service.get<ShipmentByProject[]>(this.entityUrl).subscribe(x => {this.ShipmentList = x });
  }


 ngOnInit() {
  var flags= [];
  var l = Array.isArray(this.ShipmentList) ? this.ShipmentList.length : 0, i;
   for( i=0; i<l; i++) {
    if( flags[this.ShipmentList[i].customer_shipto_name]) continue;
    flags[this.ShipmentList[i].customer_shipto_name] = true;
    this.output.push(this.ShipmentList[i].customer_shipto_name);
  }}

For testing purposes, I utilized the output array in the HTML code:

 Output data!
<li *ngFor="let out of output">
     {{ out.customer_shipto_name }}
</li>

<div class="dx-fieldset">
<div class="dx-field">
    <div class="dx-field-label">ShipTo Account</div>
    <div class="dx-field-value">
        <dx-select-box [dataSource]="ShipmentList" displayExpr="customer_shipto_name"></dx-select-box>
    </div>
 </div>

Despite having data in ShipmentList, I do not see any results in the output. https://i.sstatic.net/w9KvS.png

Answer №1

If you want to display data from the ShipmentList when receiving information from your service or API, make sure to create an instance variable for the output. Here is an example code snippet that you might find helpful. Don't forget to troubleshoot your code if needed.

export class ReportingFilterComponent implements OnInit {
  ShipmentList: ShipmentByProject[];
  entityUrl = 'ShipmentDetail/GetByReportingProject?repPrj=000634';
  output = [];

  constructor(private service: DataService) {
  }

  ngOnInit() {
    const flags = [];
    this.service.get<ShipmentByProject[]>(this.entityUrl).subscribe(x => {
      if (x && x.length > 0) {

        this.ShipmentList = x;
        for (let i = 0; i < this.ShipmentList.length; i++) {
          if (flags[this.ShipmentList[i].customer_shipto_name]) continue;
          flags[this.ShipmentList[i].customer_shipto_name] = true;
          this.output.push(this.ShipmentList[i].customer_shipto_name);
        }
      }

    });
  }
}

Answer №2

If your

service.get<ShipmentByProject>[]>
call returns a promise, it seems like this.ShipmentList will be undefined until the promise is resolved. To avoid errors, you can either initialize the value as an empty array or check for its presence before trying to access its length.

You have a few options for initializing ShipmentList:

class YourClass {
    ShipmentList = [];

    constructor() {
        // ...
    }
}

Alternatively, you can initialize it in the constructor:

constructor() {
    this.ShipmentList = [];
    service.get<ShipmentByProject[]>(this.entityUrl).subscribe(x => 
{this.ShipmentList = x });
  }
}

Or, you can check for its existence before accessing its length:

var l = Array.isArray(this.ShipmentList) ? this.ShipmentList.length : 0;

Answer №3

Ensure you are working with data that has already been loaded. The code within the ngOnInit method should be placed in the subscribe block above.

As pointed out by @Ash, the output property needs to be a class property and not initialized inside the ngOnInit.

Remember: avoid using var, opt for const or let instead as they are scoped within the block where they are declared.

Additionally, use camelCase when writing in Typescript, meaning ShipmentList should be changed to shipmentList

Answer №4

The error you're encountering seems to be originating from your ngOnInit section. Have you checked if this.ShipmentList is defined?

In addition, in order to access output within your angular template, it must be a property that belongs to the component class. Make sure to declare public output = [] at the beginning of your class and reference that variable instead.

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

Guide to iterating through an array within an object in Vue.js

Can someone help me with looping through data fetched from an API using a GET request in Vue.js? This is the sample response obtained: "data": { "Orders": [ { "OrderID": 1, "Ordered_Products": { ...

Utilizing a dictionary within an Angular controller

Currently, I am working on a complex process that involves Angular and MVC controllers interacting with a REST API to retrieve configuration items. The challenge lies in transforming this data into a usable format within the Angular controller for various ...

Require modification of JSON values in React Promise code

Looking to modify the data returned from a promise and wrap a link around one of the fields. Here is the React code: this.state = { medications: [], } queryMeds().then((response) => { this.setState({medications: response}); }); The response c ...

Generate a custom map by utilizing JavaScript and HTML with data sourced from a database

Looking for guidance on creating a process map similar to this one using javascript, html, or java with data from a database. Any tips or suggestions would be appreciated. https://i.sstatic.net/tYbjJ.jpg Thank you in advance. ...

Is there a way to showcase my information on flash cards using JavaScript?

Currently, I am developing a full stack application that utilizes JavaScript on both the front and back end. This application allows users to create their own flashcards set. Upon clicking "View Cards," the data is fetched and the question-answer pair is d ...

Issue with angular 8 radio button not being selected

Here is the HTML code I am working with: <div *ngFor="let option of systemEquipmentGroup"> <h5>{{option.optionGroupName}}</h5> <div> <label style="display: block;" * ...

"Troubleshooting: Ajax error 'Uncaught ReferenceError: data is not defined' on the

Upon checking the Chrome console, the error message displayed is : Uncaught ReferenceError: data is not defined function list(){ $.ajax({ type:'POST', url:'adeneme.php', data:$('#form1').seri ...

Innovative ways to design a responsive carousel with Bootstrap

My goal was to create a slider with divisions inside a bootsrap carousel, and here is what I did. However, I am looking for guidance on how to adjust it so that on screens smaller than sm (of bootstrap), there are only two divisions in one carousel, and a ...

No code is appearing on the page, just a blank space

Whenever I visit this page on the web, the screen shows up as empty and I've encountered similar issues with other JavaScript pages that I've created. This makes me wonder if there might be a missing piece of code or something else causing the pr ...

Tips for verifying the presence of a specific value within an array of union types

Given an array of a specific union type, I am trying to determine if a string from a larger set that includes the union type is present in the array during runtime: const validOptions: ("foo" | "bar")[] = ["foo", "bar"] type IArrType = typeof validOptions ...

Exploring Typescript Logging with Bunyan and Logentries

Looking to implement remote Logging using logentries.com for my ionic app. Snippet from my package.json: "dependencies": { "bunyan": "^1.8.5", "bunyan-logentries": "^1.2.0", }, "devDependencies": { "@types/bunyan": "0.0.35", "@typ ...

The regular expression used for validating domains does not function properly in the Safari browser

I am struggling with a JavaScript regular expression error that Safari is giving me. I am trying to validate a domain, but for some reason, this specific part (?<!-) is causing the issue because the domain name should not end with a hyphen. ^((?!-)[A-Z ...

Retrieving the current value of the selected option using JQuery

I am working on a feature where I have different quantities in selects after each button click. <button type="button" class="btn btn-sm btn-primary" id="addtocart2" >Button1</button> <select id="quantity1" class="ml- ...

Send PHP data through AJAX and retrieve it on a different PHP page

I need to send a variable through an AJAX URL to another PHP page and retrieve it using: $id=$_GET['id']; Here's an example where the value is passed, for instance $id=6. <a id="pageid" href="ifsc-bank.php?id=<?=$id?>"><im ...

Choose a variety of table rows based on the values of the data attributes that are

Is there a more efficient way to select all rows with data attributes id 1,2.. without specifying each row individually? I need some guidance on the best approach for this. Can anyone help me out? <table id="eTable"> <tr data-empid="A123" data- ...

One of the three identical paths in Node.JS is experiencing issues

I'm brand new to Node.js and currently working on creating a backend api for a project. I have 3 routes in my application: societies, users, and emails. //module for email functionality emailsModule = require('./api/routes/emails')(co ...

Is it possible to include multiple spyObjs within a beforeEach block?

In the process of testing an Angular 1 application using Jasmine, I have encountered a dilemma. My question is, can two spies be created for two different services within the same beforeEach statement? Currently, I have managed to make the first spy work ...

Generate the Xpath for the mentioned href element to use with Selenium Webdriver

I need help creating the Xpath for a specific href element using Selenium webdriver with only IE browser. The HTML code I am working with is as follows: I am looking to find the Xpath for: . Can someone assist in generating the correct Xpath expression ...

having difficulty deactivating matInput within angular form

I am facing an issue with a form where I need to disable one of the inputs based on a certain condition. <mat-form-field> <input matInput formControlName="domain" [disabled]="!is_staff && recipients[selectedIndex].verified"> </m ...

Grab the URL from React Router

I need assistance with writing a function that updates the current location to match the route of a clicked button. Currently, the code is returning the URL of the page where the button was clicked, not the path related to the button itself. Are there an ...