2
votes

I've been searching for quite awhile and haven't been able to find anything specific on how to do this. The closest thing I could find was this: How to get the value from ion-select option

I'm trying to figure out how to collect the data selected or entered on a page and put it into an array for http post? .. Would appreciate any examples or direct me to some good documentation.

ionic info:

Cordova CLI: 7.0.1 Ionic Framework Version: 3.5.3 Ionic CLI Version: 2.1.12 Ionic App Lib Version: 2.1.7 Ionic App Scripts Version: 2.0.2 ios-deploy version: 1.9.1 ios-sim version: 6.0.0 OS: OS X El Capitan Node Version: v4.3.2 Xcode version: Xcode 8.2.1 Build version 8C1002

1

1 Answers

1
votes

Ok you can try this.

Base on the link . you can try this code

on html

<ion-item>
    <ion-label>place</ion-label> 
    <ion-select [(ngModel)]="selected">
     <ion-option value="item" *ngFor="let item of options">
      {{item.name}} &nbsp;&nbsp;{{item.price}}</ion-option> 
    </ion-select>
</ion-item>

<div padding>
   <button  ion-button (tap)="addOption()" block>Add Option</button>
   <button  ion-button (tap)="PostSelected()" block> Sync </button>
</div>

then in your page component.

    import { Http, RequestOptions, Headers } from '@angular/http';
    import 'rxjs/Rx'; 

   //first declare your ngModel variable and you post array variable
    selected:any;
    SelectedArray = []; 

    addOption(){
      this.SelectedArray.push(this.selected);
    }

    PostSelected(){

      let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });

      let options = new RequestOptions({
      headers: headers,
      method: "POST"
      });

      let bodu = JSON.stringify(this.SelectedArray)

      let result =  this._http.post(link, body, options).timeout(30000);
      result.subscribe(data => {
         console.log('result sucess',data)
      },error=>{
         console.log('result error',data)
      })
    } 

UPDATE

addOption(){
      let validate = this.SelectedArray.filter(res=>{
            return res == this.selected;
      });

      // if validate length is 0 the new value of this.selected is currently not found on this.SelectedArray so its ok to be push
      if(validate.length == 0){
        this.SelectedArray.push(his.selected)
      }else{
        //  else do other thing
      } 
    }