我的应用程序具有一个带有选择选项的表单,对于这些选项,他们需要具有来自Web api的数据。结构是:
result: Array(749)
[0 … 99]
0: "0000105862"
1: "0000105869"
2: "0000105875"
3: "0000110855"
4: "0000110856"
5: "0000110859"
6: "0000111068"
7: "0000111069"
8: "0000111077"
9: "0000112050"
etc
我正在尝试将其绑定到select选项中,我通过服务来执行此操作,但是这些值未显示出来?
html结构:
<select formControlName="sys_id" class="form-select">
<option *ngFor="let state of sys_id" [ngValue]="state">
{{ state }}
</option>
</select>
ts文件:
public sys_id = [];
private getSys() {
this.service.getSys(this.customer_id).subscribe((data) => {
this.loading = true;
console.log('Data' + data);
this.loading = false;
console.log('Result - ', data);
console.log('data is received');
})
}
ngOnInit() {
this.getSys();
this.serviceForm = new FormGroup({
customer_id: new FormControl(this.customer_id),
sys_id: new FormControl(this.sys_id[0], Validators.required),
});
}
service.ts
getSys(customerId): Observable<any> {
return this.http.get<any>(this.sysApiUrl + "?customer_id=" + customerId)
.pipe(
catchError(this.handleError)
);
}
答案 0 :(得分:1)
看来您的sys_id是一个空数组。
我认为您需要在getSys()方法中分配数据。
this.service.getSys(this.customer_id).subscribe((data) => {
this.loading = true;
console.log('Data' + data);
for(var i = 0; i < data.length; i++){ // loop through the object array
this.sys_id.push(data[i]); // push each element to sys_id
}
this.loading = false;
console.log('Result - ', data);
console.log('data is received');
})
答案 1 :(得分:0)
通过评论回答您的问题。现在,您不必担心取消订阅或订阅。另外,您正在使用类型,这是打字稿的优势之一。
Model.ts
export interface YourData {
name: string;
value: number;
}
component.ts
your_array: Observable<YourData>
ngOnInit() {
this.your_array = yourService.getData()
}
Service.ts
return this.http.get<YourData>(this.sysApiUrl + "?customer_id=" + customerId)
.pipe(
catchError(this.handleError)
);
template.html
<option *ngFor="let state of sys_id | async" [ngValue]="state">