提问者:小点点

Angular,在同一个html页面上多次显示一个列表,在C#循环的每一轮循环中都会更新该列表


我希望在循环中的每一轮中,当列表将根据当前的div更新时,显示一个列表作为选择中的选项。它在概念上起作用,但是html只根据列表中的最后一个条目更新一次,并且不会为每个循环旋转显示不同的列表

我的html

<div *ngFor="let item of listConstraint" [value]="item.id">
        <p>{{item.name_constraint}}</p>
        <select>
            <option *ngFor="let item1 of listConstraintDetails" [value]="item1.id">
                {{item1.name_constraint}}</option>
        </select>
    </div>

我的ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { AjaxRequestService } from 'src/app/services/Request/ajax-request.service';
import { ConstraintKind } from 'src/app/class/constraintKind';
import { ConstraintDetails } from 'src/app/class/constraint-details';

@Component({
  selector: 'app-constraints',
  templateUrl: './constraints.component.html',
  styleUrls: ['./constraints.component.css']
})
export class ConstraintsComponent implements OnInit {
  constraintForm: FormGroup;
  listConstraint: ConstraintKind[] = [];
  listConstraintDetails: ConstraintDetails[] = [];
  constructor(private http: AjaxRequestService, private httpClient: HttpClient, private route: Router) {

  }

  ngOnInit(): void {
    this.GetConstraintsKind();
  }
  GetConstraintsKind() {
    return this.http.GetConstraintsKind().subscribe(data => {
      this.listConstraint = data;
      data.forEach(element => {
        this.GetConstraintsDetails(element.id);
      })
      console.log(data);
    })
  }
  GetConstraintsDetails(constraintId) {
    return this.http.GetConstraintsDetails(constraintId).subscribe(data => {
      this.listConstraintDetails = data;
      console.log(data);
    })
  }
}

my functions ajax服务

  GetConstraintsKind() {
    return this.http.get<any>('http://localhost:11818/Api/Constraint/getConstraintKind', { headers: this.header });
  }
  GetConstraintsDetails(constraintId: number) {
    return this.http.get<ConstraintDetails[]>('http://localhost:11818/Api/Constraint/GetConstraintsDetails/' + constraintId);
  }

服务器运行良好,并且发送了正确的数据,但是html始终显示相同的列表,非常感谢您的任何帮助


共1个答案

匿名用户

您正在单个数组中的ngOnInit上执行内部循环操作,这将覆盖listConstraintDetails数组中先前获取的数据。

如果您稍微修改一下代码,就可以实现您想要的目标,就像这样

null

  ngOnInit(): void {
    this.GetConstraintsKind();
  }
  GetConstraintsKind() {
    return this.http.GetConstraintsKind().subscribe(data => {
      this.listConstraint = data;
    })
  }
  GetConstraintsDetails(constraintId):ConstraintDetails[]{
  let itemsarr: ConstraintDetails[] = [];

  if(constraintId)
  {
   this.http.GetConstraintsDetails(constraintId).subscribe(data => {
   itemsarr = data;
   })
  }
   return itemsarr;
  }