如何绑定Web API数据以在Angular 6中形成SELECT选项



我的应用程序具有一个具有选择选项的表单,对于他们需要从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)
      );
  }

看起来您的sys_id是一个空数组。

我认为您需要在getys()方法中分配数据。

 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">

最新更新