【问题标题】:ngFor is not populating values properlyngFor 没有正确填充值
【发布时间】:2023-03-11 10:07:01
【问题描述】:

我现在尝试使用数据库中的值填充下拉列表,当我尝试在 ul 标记内使用 ngFor 时,它只显示第一个值,但它应该显示两个值,因为我在数据库中有两个值,而且GET 请求给了我一个大小为 2 的数组。所以我尝试将 ngFor 保留在其他标签中,然后它给了我两个值,但所有内容都以 2 个数字出现,因为 for 循环正在工作,它正在复制所有内容。

模板

<div class="dropdown">
  <button (click) = "dd()" class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
    Select Doctor
  </button>
  <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1" *ngFor="let d of doctor">
    <li><a class="dropdown-item" href="#">{{d.name}}</a></li>
  </ul>
</div>

组件.ts

  patientForm: FormGroup;
  doctor: Doctor[];

  constructor(private doctorService: DoctorService) { }

  ngOnInit(): void {
    this.patientForm = new FormGroup({
      name: new FormControl('', [Validators.required]),
      illness: new FormControl('', [Validators.required]),
      // doctorId: new FormControl('', [Validators.required])
    })
    this.doctorService.getDoctor().subscribe(data=>{
      this.doctor = data;

      // checking if the data is coming and going into the array
      console.log(this.doctor);
    })
  }

这是我在控制台中得到的内容

  (2) [{…}, {…}]
  0: {id: 1, name: "Dr.Subhajit", degree: "MD", specialization: "Heart"}
  1: {id: 2, name: "Dr.Tamanash", degree: "MD", specialization: "Brain"}
  length: 2
  __proto__: Array(0)

这是我的服务

  private getApi: string = 'http://localhost:8080/doctor'
  constructor(private http: HttpClient) { }

  public getDoctor() : Observable<Doctor[]>{
    return this.http.get<Doctor[]>(this.getApi);
  }

【问题讨论】:

  • 您能否从后端和前端验证您的服务的输出,并可能将其添加到问题中。
  • 已更新,而且我从 api 中正确获取了所有值,当我在 ul 标记内使用 ngFor 时它无法正常工作
  • 您的服务看起来也不错。如果将 *ngFor="let d of doctor" 移动到 li 标签会发生什么?还是只有一名医生?您的浏览器控制台中是否还有其他消息?
  • 您是否给样式表中的下拉类指定了一个高度?
  • 是的,我将 ngFor 从 ul 移到 li,问题得到解决,我明白为什么会这样

标签: angular ngfor


【解决方案1】:

当我对包含 2 位医生的数组进行硬编码时,您的示例对我来说效果很好。

my example on stackblitz

但是,我会将 *ngFor 移动到

  • 元素。现在您正在创建多个无序列表。

    问题一定出在你的服务的某个地方,或者在后端。

    尝试打印您从服务中获取的数据:

    this.doctorService.getDoctor().subscribe(data=>{
      console.log(data);
      this.doctor = data;
    })
    

    并在浏览器开发工具中查看您从该服务中获得了什么。

  • 【讨论】:

    • 您可以将 DoctorService 添加到您的问题中吗?可能您的请求有问题。
    • 添加了,看看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    相关资源
    最近更新 更多