Angular NgRx-如何在模板html中查看商店中的对象?

时间:2019-12-13 12:43:47

标签: angular ngrx

嘿,我要存储对象,我想在模板中查看对象。

我的Ts文件:

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() {
  }

}

我的模板:

<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>

我在控制台中出现的错误:

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

我尝试这样做,但不起作用:

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

图像,如果我的状态: enter image description here

3 个答案:

答案 0 :(得分:3)

您需要的是将asynckeyvalue管道组合在一起。管道的顺序也很重要:

<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>

以下是此代码的演示堆栈:https://stackblitz.com/edit/angular-1rj8sc

答案 1 :(得分:1)

这是正确的方法:

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

首先,您需要使用异步管道让Angular订阅可观察的对象,在* ng内使用它,否则将尝试迭代尚不存在的对象。接下来使用* ngFor创建多个<li>元素,而不是<ul>

答案 2 :(得分:0)

如果状态片“用户”已规范化并存储为键为object结构的对象,则需要将其转换为数组以在模板中对其进行迭代。

您可以轻松地将其转换为类似这样的数组

  private userDetails: User;
  constructor(private store: Store<AppState>) {
    this.comment$ = this.store.select('comment');
    // Use Object.values() to convert to an array with all the values of that object
    this.userDetails$ = this.store.select('user').subscribe(userDetails => {
     this.userDetails = Object.values(userDetails);
    });
  }

  // Then

  <li *ngFor="let item of userDetails">
    <ul>{{item}}</ul>
  </li>

尽管很难在不了解数据结构的情况下确切知道发生了什么。

其他一些注意事项:如果userDetails只是一个对象,并且您想遍历每个属性并获取键和值,请使用Object.entries()

相关问题