仅显示 Selectbox/dropdown 中的唯一值

Showing only unique Values in the Selectbox/dropdown

我正在尝试从 SQL 服务器数据库获取数据并将响应放入前端的字段中。我正在获取数据,但响应中的某些字段不是唯一的,并且在下拉列表中显示重复值。我的组件如下所示

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);
  }}

为了测试,我在 html

中使用了 output 数组
 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>

我在 output 中没有得到任何东西,尽管 ShipmentList 上有数据。

所以抛出的错误是在你的 ngOnInit 块中。 this.ShipmentList 是否未定义?

此外,要在您的 angular 模板中访问 output,它需要是 属性 组件 class.在 class 的顶部,您应该放置 public output = [] 并将其作为目标。

假设您的 service.get<ShipmentByProject>[]> 调用 returns 承诺,在承诺解决之前,this.ShipmentList 似乎是未定义的。您可以将该值初始化为空数组以消除错误,或者在尝试读取长度之前检查它是否存在。

你可以提前初始化ShipmentList

class YourClass {
    ShipmentList = [];

    constructor() {
        // ...
    }
}

或者在构造函数中初始化:

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

或者在读取长度之前检查它:

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

您正在使用尚未加载的数据。你在 ngOnInit 方法中的内容应该在上面的订阅中。

正如@Ash 提到的,output 属性 应该是 class 属性 而不是在 ngOnInit.

中定义

注意 1:不要使用 var,而是使用 constlet。因为这两个存在于它们所在的块中。

注2:在Typescript中使用驼峰式,所以例如ShipmentList应该是shipmentList

当从您的 service/api.

返回数据时,您可能想要显示 ShipmentList 的数据

此外,您需要用于输出的实例变量。像下面这样的东西。尝试调试您的代码。

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);
        }
      }

    });
  }
}