简体   繁体   中英

Angular2 - ngFor single object vs array

I have a situation where I receive an object of data from my database that contains records for versions of a file. There could be 5 versions (5 records) or a single version returned.

My issue is that I am using ngFor to loop over the array of data and print them to the table. In the event that there is only a single record returned, the data is no longer an array of objects and is just a single object.

<tbody class="ruleVersions">
 <tr *ngFor="let m of mapData.ruleVersion.x">
  <td class="small">V {{ m.RuleVersion }}.0</td>
  <td [innerHtml]="m.CreatorNTID | ntidLink"></td>
  <td class="small">{{ m.VersionNotes ? m.VersionNotes : 'N/A' }}</td>
  <td class="small">{{ m.BasedOnRuleVersionID ? m.BasedOnRuleVersionID : 'N/A' }}</td>
  <td class="small">{{ m.MetaInsertUtc }}</td>
 </tr>
</tbody>

Multiple Records:

在此处输入图片说明

Single Record:

在此处输入图片说明

This poses a problem because the ngFor is set up to loop over arrays. Due to the single record not being an array of objects like when there are multiple, it throws this error:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

What is the best way to solve for this? Is there anything in angular I can use to treat the data as an array even if its not, perhaps with a pipe of some sort?

The only other way I can think of is passing the entire object through a function and having it push objects into arrays if its a single record. That then poses the problem of not wanting every single record to be an array.

Just curious if there are any built in angular ways to solve for this?

Update:

I solved this by creating a pipe.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'isArray' })
export class IsArrayPipe implements PipeTransform {
    transform(x): any {
        return Array.isArray(x) ? x : [x];
    }
}

<tr *ngFor="let m of mapData.ruleVersion.x | isArray: x">

When you get your response, you can check if it's array or not. If it's not an object, you can set the object in an array, so something like this in service:

getData() {
  return this.http.get('url')
    .map(response => {
      let res = response.json();   
      if(!Array.isArray(res)) {
         return [res]    
      }  
      return res;
    })
}

So now, no matter if you get an array or an object, it's always iterable with *ngFor as the component always receives an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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