Angular 2:如何将GET服务响应数据绑定到下拉列表

时间:2017-02-21 12:36:19

标签: html angularjs angular typescript

Clientlist.service.ts

     getClientList()
   { 
     let headers = new Headers();
     headers.append('Content-Type', 'application/json');
     let authToken = localStorage.getItem('auth_token');
     console.log(authToken);
     headers.append('X-auth-Token', authToken)
      return this._http.get('http://localhost:8080/api/v1/client/list?isClient=Y', {headers})
      .map((res) => {
      var clientList = res;
      console.log(clientList);
    })
  }

回复:

[{"userId":"mind.com","clientCode":"75","clientName":"ABC COMPANY, THE"},{"userId":"mind.com","clientCode":"51","clientName":"infotech"}]

这里我在clientList中获取了一个客户端列表,现在我怎样才能将这个响应绑定到角度为2的下拉列表中。请帮助我。

2 个答案:

答案 0 :(得分:1)

您需要创建以下客户端对象的对象,在下拉列表中解析和显示变得更加容易。

以下是客户的模型:

export class Client
{
userId: string;
clientCode: string;
clientName: string;
}

在component.ts中创建对象后:

clients: Client[];
currentSelection: Client;

ngOnInit()
{
//... do your calls do get res(client list)
var clientList = res;
this.clients = JSON.parse(clientList);
}
onChange(value: Client)
{
this.currentSelection = value;
}

然后在你的html代码中执行以下操作:

<select (change)="onChange($event.target.value)">
    <option *ngFor="let client of clients">{{client.clientName}}</option>
</select>

答案 1 :(得分:1)

您可以像

一样使用它
<select [(ngModel)]="client.clientCode">
      <option value="" disabled selected>Select Client Name</option> 
      <option *ngFor="let user of ClientList" [value]="user.clientCode">{{user.clientName}}</option>
</select>