简体   繁体   English

如何将Web API数据绑定到Angular 6中的表单选择选项

[英]How to bind web api data to form select option in Angular 6

My application has a form which has a select option, for the options they need to have the data from a web api. 我的应用程序具有一个带有选择选项的表单,对于这些选项,他们需要从Web api获取数据。 structure is: 结构是:

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

I am trying to bind this into the select option, I am doing this via a service, but the values are not showing up? 我试图将其绑定到选择选项中,我通过服务来执行此操作,但是没有显示值?

html structure: html结构:

<select formControlName="sys_id" class="form-select">
    <option *ngFor="let state of sys_id" [ngValue]="state">
    {{ state }}
    </option>
</select>

ts file: 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 service.ts

getSys(customerId): Observable<any> {
    return this.http.get<any>(this.sysApiUrl + "?customer_id=" + customerId)
      .pipe(
        catchError(this.handleError)
      );
  }

It looks like your sys_id is an empty array. 看来您的sys_id是一个空数组。

I think you need to assign the data in your getSys() method. 我认为您需要在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');
})

To answer your question from your comment. 从您的评论中回答您的问题。 Now you dont have to worry about unsubscribing or subscribing. 现在,您不必担心取消订阅或订阅。 Plus you are using types which is one of the advantages of typescript. 另外,您正在使用类型,这是打字稿的优势之一。

Model.ts Model.ts

export interface YourData {
name: string;
value: number;
}

component.ts component.ts

 your_array: Observable<YourData>

 ngOnInit() {
    this.your_array = yourService.getData()
 }

Service.ts Service.ts

 return this.http.get<YourData>(this.sysApiUrl + "?customer_id=" + customerId)
  .pipe(
    catchError(this.handleError)
  );

template.html template.html

 <option *ngFor="let state of sys_id | async" [ngValue]="state">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM