gpt4 book ai didi

Angular - 选择下拉列表为空

转载 作者:行者123 更新时间:2023-12-02 18:35:04 25 4
gpt4 key购买 nike

在我的 Angular-12 中,我有来自 API 端点的 JSON 响应:

{
"message": "vehicle Model Detail.",
"error": false,
"code": 200,
"results": {
"vehiclemakes": [{
"name": "Freightliner",
"id": 15
},
{
"name": "Honda",
"id": 13
},
{
"name": "Renault",
"id": 3
},
{
"name": "Suzuki",
"id": 16
},
{
"name": "Toyota",
"id": 4,
},
{
"name": "Volkswagen",
"id": 6
},
{
"name": "Volvo",
"id": 5
}
]
}
}

服务:

public getParameters(): Observable<any> {
return this.http.get(this.api.baseURL + 'parameters', this.httpOptions);
}

组件:

vehicles!: any[];

loadAllVehicles() {
this.vehiclemodelService.getParameters().subscribe(
data => {
this.vehicles = data.results.vehicles;
},
error => {
this.store.dispatch(loadErrorMessagesSuccess(error));
}
);
}

ngOnInit(): void {
this.loadAllVehicles();
}

我要将其加载到下拉选择列表中:

HTML:

<ng-select [items]="vehicles"
[selectOnTab]="true"
[searchable]="true"
bindValue="name"
bindLabel="make_id"
placeholder="Select Vehicle Make"
[multiple]="false"
[clearable]="true"
required
formControlName="make_id">
</ng-select>

当我加载表单并单击选择下拉列表时,似乎有数据但没有显示任何内容。

如何解决这个问题?

谢谢

最佳答案

因为 this.vehicles 是异步填充的,所以 .subscribe() 就是这样工作的。当您的 ng-select 呈现时, this.vehicles 不包含您的 api 响应。

处理这个问题的简单方法:

html:

<ng-select [items]="vehicles$ | async"
[selectOnTab]="true"
[searchable]="true"
bindValue="name"
bindLabel="make_id"
placeholder="Select Vehicle Make"
[multiple]="false"
[clearable]="true"
required
formControlName="make_id">
</ng-select>

ts:

vehicles$!: Observable<any[]>;

loadAllVehicles() {
this.vehicles$ = this.vehiclemodelService.getParameters().pipe(
map(data => data.results.vehicles)
catchError(() => {
this.store.dispatch(loadErrorMessagesSuccess(error));
return of(null);
}),
);
}

ngOnInit(): void {
this.loadAllVehicles();
}

关于Angular - 选择下拉列表为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68899513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com