【发布时间】: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,问题得到解决,我明白为什么会这样