Tom
Tom

Reputation: 8681

Angular : Map error: NgFor only supports binding to Iterables such as Arrays

I am subscribing to an obserable to get data which works fine in angular 8. I need to format the date when using mapping I get error saying

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

So I believe adding the map operator and changed the return type. I am not sure whats wrong in the way that i have implemented the map. Could somebody let me know ?

export interface IPersonNote {
    id: number;
    personId: number;
    note: string;
    authorId: number;
    authorName: string;
    fileName: string;
    mimeType: string;
    alias: string;
    createdBy: string;
    createdDate: Date;
}

Original method

import { map } from 'rxjs/operators';
public personNotes: IPersonNote;

   loadPersonNotes() {
        this.isCurrentUser = this.id !== this.userService.getCurrentUser().id;
        this.userService.getPersonNote(this.id)
          .subscribe((x: IPersonNote) => {

            this.personNotes = x;
          });
      }

Modified method

import { map } from 'rxjs/operators';
public personNotes: IPersonNote;

loadPersonNotes() {
    this.isCurrentUser = this.id !== this.userService.getCurrentUser().id;
    this.userService.getPersonNote(this.id)
      .pipe(map(note => <any>{
        createdDate: format(note.createdDate, 'Do MMM YYYY'),
      }))
      .subscribe((x: IPersonNote) => {

        this.personNotes = x;
      });
  }

UI

<div *ngIf="personNotes">
<div class="portlet-body">
    <ul class="tier-history">
      <li *ngFor="let note of personNotes">
        <span class="tier-title"> {{ note.authorName }} </span>
        <span class="tier-dates">
            {{ note.created }} 
        </span>
        <span class="tier-title"> {{ note.note }} </span>
      </li>
    </ul>
  </div>
</div>

Service

public getPersonNote = (id: number): Observable<IPersonNote> =>
this.http.get<IPersonNote>(`${this.baseUrl}person-note/${id}`)

Upvotes: 1

Views: 143

Answers (1)

Alexander Trakhimenok
Alexander Trakhimenok

Reputation: 6278

You method returns wrong data.

It should be like this (pay attention to the type of variable in subscribe):

   public personNotes: IPersonNote[]; // Not a single but few notes (or none)

   loadPersonNotes() {
        this.isCurrentUser = this.id !== this.userService.getCurrentUser().id;
        this.userService.getPersonNotesByUserId(this.id)
          .subscribe((personNotes: IPersonNote[]) => {

            this.personNotes = personNotes;
          });
   }

Upvotes: 2

Related Questions