我的应用程序有一个表单,它有一个选择选项,用于获取来自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
我试图将它绑定到选择选项,我通过服务这样做,但值没有显示?
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)
);
}
看起来你的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');
})
从您的评论中回答您的问题。现在您不必担心取消订阅或订阅。另外,您使用的类型是打字稿的优点之一。
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">