Gajanan Shinde
Gajanan Shinde

Reputation: 133

in angular 6= ERROR: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

Please help me to solve this error

ProfileComponent.html:4 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
    at DefaultIterableDiffer.push../node_modules/@angular/core/fesm5/core.js.DefaultIterableDiffer.diff (core.js:5642)
    at [enter image description here][1]NgForOf.push../node_modules/@angular/common/fesm5/common.js.NgForOf.ngDoCheck (common.js:3156)
    at checkAndUpdateDirectiveInline (core.js:9246)
    at checkAndUpdateNodeInline (core.js:10507)
    at checkAndUpdateNode (core.js:10469)
    at debugCheckAndUpdateNode (core.js:11102)
    at debugCheckDirectivesFn (core.js:11062)
    at Object.eval [as updateDirectives] (ProfileComponent.html:4)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:11054)
    at checkAndUpdateView (core.js:10451)

Below are my files

PRofile.service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Iprofile } from './profile';
import {Observable} from 'rxjs/';

@Injectable({
  providedIn: 'root'
})
export class ProfileService {
  private _url:string='https://jsonplaceholder.typicode.com/todos/1';

  constructor(private http:HttpClient) { 
  }
    getProfile():Observable<Iprofile[]>{
      return this.http.get<Iprofile[]>(this._url)

    }

}

Profile component.ts

import { Component, OnInit,Input } from '@angular/core';
import {ProfileService} from '../profile.service'
@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
@Input()
export class ProfileComponent implements OnInit {

  public profiles=[];
  constructor(public profservice:ProfileService) { }

  ngOnInit() {
   this.profservice.getProfile()
    .subscribe(data => this.profiles =data);
  }
}

profile.component.html

 <p>
      profile works!
    </p>
    <ul *ngFor="let profile of profiles">
        <li>{{profile.id}}</li>
      </ul>

profile.ts

export class Iprofile{
    userId: number;
    id: number;
    title: string;
    completed : boolean
  }

Upvotes: 1

Views: 6825

Answers (1)

Rohit Sharma
Rohit Sharma

Reputation: 3334

Actually, the URL you are using is returning only one object:

See here: https://jsonplaceholder.typicode.com/todos/1

You are passing the URI parameter that is the ID of the first object. You need to change it to:

https://jsonplaceholder.typicode.com/todos

In your case change from:

private _url: string = 'https://jsonplaceholder.typicode.com/todos/1';

to:

private _url: string = 'https://jsonplaceholder.typicode.com/todos';

Because ngFor only accepts arrays, not objects and you are passing the object so you are getting the error:

Only arrays and iterables are allowed

Upvotes: 2

Related Questions