如何使用angular2将json数据设置为选择框

时间:2017-01-09 06:06:09

标签: angular

json数据

{ "d": "[{\"batch\":\"5\",\"term\":\"TERM V\",\"section\":\"Section I\"},{\"batch\":\"5\",\"term\":\"TERM VI\",\"section\":\"Section I\"},{\"batch\":\"5\",\"term\":\"TERM VII\",\"section\":\"Section I\"},{\"batch\":\"6\",\"term\":\"TERM I\",\"section\":\"Section I\"},{\"batch\":\"6\",\"term\":\"TERM II\",\"section\":\"Section I\"}]" }      

服务

getwithParamter()    
{
  let params = {program: 'pravin'};
  this.headers = new Headers();
  this.headers.append('Content-Type', 'application/json; charset=utf-8');
  //this.headers.append('Parameter',  params);
  let options = new RequestOptions({
                method: RequestMethod.Post,
                url: "AttendanceMast.aspx/getBatch",                   
                headers: this.headers,
                body:{program: 'IFDM',location:'Pune',createdby:'ifdmpune'}
                });

  return this._http.request(new Request(options)).retry(2)
             .map((response: Response) =>  JSON.parse(response.text()))
            .do(data => console.log('All: ' + data))
            .catch(this.handleError);                  

 }

ts文件

  this.dataService.getwithParamter().subscribe(
  tradeshows => this.getwithparamter = tradeshows,
  error => console.error('Error: ' + error)
);

的HTML

 Batch : <select  [(ngModel)]="sel_batch"  > <option >Select Batch</option>
                   <option *ngFor="let item of  getwithparamter   ">{{item.batch}}</option>

问题

我想将batchjson data设置为select box,请参阅上面的json数据来自JsonConvert.SerializeObject如何转换正常数组ngFor < / p>

怎么做?

1 个答案:

答案 0 :(得分:1)

未经测试的代码:您可以尝试这样做:首先解析JSON,如下所示:

TS:

  something: any;

  this.dataService.getwithParamter().subscribe(
    tradeshows => { 
      this.something = tradeshows
      this.getwithparameter = JSON.parse(this.something.d)
  });

并查看:

<option *ngFor="let item of getwithparamter">{{item.batch}}</option>
你可以尝试在你的html视图中

  <option *ngFor="let item of getwithparamter.d">{{item.batch}}</option>

TS:

  this.dataService.getwithParamter().subscribe(
    tradeshows => { 
      this.getwithparameter = tradeshows
  });

如上所述,这没有经过测试,请告诉我是否有效!