zaqwsx
zaqwsx

Reputation: 63

Angular / how can i convert fetched data from string to array

i have edit form in dialog, but api data for select i am receiving is in string not array so i get this error:

Error: Value must be an array in multiple-selection mode.

campaign.ts

  ngOnInit(): void {
    this.fetchdata();
  }

  fetchdata() {
    this.campaignService.sendGetRequest()
    .subscribe((data: any[])=>{
      this.campaigns = data;
    })
  }

  onEdit(item){
    this.campaigns.findIndex(i => i.id == item.id);
    const dialogRef = this.dialog.open(EditComponent,{
          data: item
        });
  }

edit.ts

this.editForm = this.fb.group({
  Name: this.data.name,
  SmsText: [this.data.smsText,  [Validators.required]],
  SmsSendDate: [this.data.smsSendDate,  [Validators.required]],
  SmsSendHoursRange: this.fb.group({
    start: [this.data.smsSendHoursRange.start,  [Validators.required]],
    end: [this.data.smsSendHoursRange.end,  [Validators.required]],
  }),
  Branch: [this.data.branch],
  InspectionResult: [this.data.inspectionResult],
  Categories: [this.data.categories],
  DateOfIssue: [this.data.dateOfIssue],
  Brand: [this.data.brand],
  VehicleCategory: [this.data.vehicleCategory],
  OwnerStatus: [this.data.ownerStatus],
  IsPhys: [this.data.isPhys],
  IsJRDC: [this.data.isJRDC]
});

// get centers
this.campaignService.getCenters().subscribe((data: any[])=>{
  this.centers = data;
})
// get vehicles
this.campaignService.getCategories().subscribe((data: any[])=>{
  this.categories = data;
})

edit.html

  <div class="column">
    <mat-form-field appearance="fill">
      <mat-label>Car category</mat-label>
      <mat-select multiple formControlName="Categories">
        <mat-option *ngFor="let item of categories" [value]="item.id">{{item.description}}</mat-option>
      </mat-select>
    </mat-form-field>
  </div>
<div class="columns">
  <mat-form-field appearance="fill">
    <mat-label>Centers</mat-label>
    <mat-select multiple formControlName="Branch">
      <mat-option *ngFor="let item of centers" [value]="item.centerCode">{{item.address}}</mat-option>
    </mat-select>
  </mat-form-field>
</div>

this is api response which i want to convert in array for select

branch: "G25,G22"
brand: "OPEL, SUBARU"
inspectionResult: "1"
...............

Upvotes: 1

Views: 391

Answers (2)

Dano
Dano

Reputation: 254

In javascript there is a function split(separator), which splits a string into an array by the separator.

So in your case, when you construct the formGroup, you would set, for instance:

Branch: [this.data.branch.split(',')],

Upvotes: 2

Bob
Bob

Reputation: 14654

/**
  split the input in lines (\n) then for each line
  extract on array assuming that the key name is composed with only non-space characters
  that in the right hand side there are no escaped quotes and that `,` is always an item 
  separator.
  returns {Map<string, string[]>}
*/
function parseResponse(s){
  const keyValue = /\s*(\S+?)\s*:\s*"(.*?)"\s*/
  const result = {}
  const LINE_SEPARATOR = '\n'
  for(line of s.split(LINE_SEPARATOR)){
    const match = line.match(keyValue)
    if(match){
      result[match[1]] = match[2].split(',').map((s) => s.trim())
    }
  }
  return result;
}

For the three first lines of your example it gives.

{
  branch: [ 'G25', 'G22' ],
  brand: [ 'OPEL', 'SUBARU' ],
  inspectionResult: [ '1' ]
}

Lines that don't match are ignored (fails silently)

Upvotes: 1

Related Questions