Search code examples
angularngrx

Angular NgRx - How to view object from the store in my template html?


Hey i have object in store and i want to view the object in the template.

My Ts File:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import { Comment } from '../../models/comment.model';
import { User } from '../../models/user.model';
import { AppState } from '../../app.state';

@Component({
  selector: 'app-ngrx-get-data',
  templateUrl: './ngrx-get-data.component.html',
  styleUrls: ['./ngrx-get-data.component.scss']
})
export class NgrxGetDataComponent implements OnInit {
  comment$: Observable<Comment[]>;
  userDetails$: Observable<User>;

  constructor(private store: Store<AppState>) {
    this.comment$ = this.store.select('comment');
    this.userDetails$ = this.store.select('user');
  }

  ngOnInit() {
  }

}

My template:

<div style="margin: auto;">
<h1 style="text-align: center;">USER DETAILS FROM API</h1>
<li *ngFor="let item of userDetails$ | async ">
  <ul>{{item}}</ul>
</li>
</div>

My Error in console:

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

I try this and its not work:

<h1 style="text-align: center;">USER DETAILS FROM API</h1>
<li *ngFor="let item of userDetails$ | keyvalue">
  <ul>{{item.key}} {{item.value}}</ul>
</li>

Image if my state: enter image description here


Solution

  • What you need is to combine async and keyvalue pipes together. Also the order of the pipes important :

    <h1 style="text-align: center;">USER DETAILS FROM API</h1>
    <ul *ngFor="let item of userDetails$ | async | keyvalue">
      <li>{{item.key}}: {{item.value}}</li>
    </ul>
    

    Here's a demo stackblitz of this code: https://stackblitz.com/edit/angular-1rj8sc