Home > front end >  Error trying to diff '[object Object]'. Only arrays and iterables are allowed but i dont s
Error trying to diff '[object Object]'. Only arrays and iterables are allowed but i dont s

Time:03-08

I have been having this problem for the past week, I have searched everywhere but wasn't able to find a problem.

My service

private texst!: Posts[];

  
  public getPosts(): Observable<Posts[]>
  { 

    return this.http.get<Posts[]>("http://localhost/projects/php_rest_api/api/post/read.php").pipe(map((data) => {
      return this.texst = data;
    }));
  }

My Component, here i add the service and run the function to get the data from my database

public test: Posts[] = [];]

  constructor(public postService: PostsService,
              private http: HttpClient) {}

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

  public getPosts()
  {
    this.postService.getPosts().subscribe((response) => {
      this.test = response;
      console.log(this.test);
    })
  }

My html

<div>
    <button (click)="getPosts()"></button>
    <div *ngFor="let test of test">
        {{test.title}}
    </div>
</div>
```

[enter image description here][1]


  [1]: https://i.stack.imgur.com/QXQuN.png

CodePudding user response:

Change this, rename your var test to testItem because it's already used:

<div>
    <button (click)="getPosts()"></button>
    <div *ngFor="let testItem of test">
        {{testItem.title}}
    </div>
</div>

CodePudding user response:

It means you're trying to iterate over object, but you think it's an array.

If that image is a log of the response, you better do:

public getPosts()
  {
    this.postService.getPosts().subscribe((response) => {
      this.test = response.data; // <.. this changes!
    })
  }

and in template:

<div *ngFor="let testItem of test">
      {{testItem.title}}
</div>
  • Related