繁体   English   中英

Angular 2:如何从 API 获取服务响应数据到 Select 选项

[英]Angular 2: How to GET service response data from API to the Select Option

Api.services.ts

 listNama() {
     return this.http.get(this.BaseURL + 'welcome/getnama')
            .pipe(map(response => {
                 return response;
            }));
 }

我得到这样的回应

{
"status": "OK",
"Output": [
    {
        "id_pemborong": "1569079912",
        "nama": "ayub"
    },
    {
        "id_pemborong": "1569125109",
        "nama": "Hartono"
    },
    {
        "id_pemborong": "1569319859",
        "nama": "agus"
    },
    {
        "id_pemborong": "1569416787",
        "nama": "joko"
    }
   ]
 }

我如何将此响应绑定到 angular 中的 Select 选项。 帮助

TS

    NameList:any[]=[];
    listNama() {
    return this.http.get(this.BaseURL + 'welcome/getnama')
      .pipe(map(response => {
      this.NameList= response.Output;
      }));
     }

Html

    <select  [(ngModel)]="selected" (change)="onChange($event)">
       <option [label] ="nama" *ngFor="let item of NameList" [selected]="selected" [value]="nama">
          {{nama}}
       </option>
    </select>

服务

listNama() {
    return this.http.get(this.BaseURL + 'welcome/getnama')
}

然后在你的组件中订阅它

/decalre a variable
NameList:any[]=[];

/ replace service with your servicename
this.service.function.subscribe(arg => this.NameList = arg);

并在模板中

<select  [(ngModel)]="selected" (change)="onChange($event)">
<option [label] ="nama" *ngFor="let item of NameList" [selected]="selected" 
  [value]="nama">{{nama}}
</option>
</select>

您的map没有做任何事情。 您需要在response Output map然后订阅 Observable 以获取该值。

api.service.ts

listNama() {
    return this.http.get(this.BaseURL + 'welcome/getnama').pipe(
        map(response => response.Output)
    );
}

然后像这样在您的组件中订阅它

import ApiService from 'path/to/api/service';
...

    namaList: Nama[];

    constructor(private apiService: ApiService) { }

    ngOnInit() {
        this.service.listNama().subscribe(data => {
            this.namaList = data;
        });
    }

Nama界面看起来像这样

export interface Nama = {
    id_pemborong: string;
    nama: string;
}

然后在模板中使用namaList以显示select中的列表。

<select>
    <option *ngFor="let item of namaList" [value]="item.id_pemborong">{{item.nama}}</option>
</select>

暂无
暂无

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

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