繁体   English   中英

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

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

嘿,我有对象在商店,我想查看模板中的对象。

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

图像如果我的状态: 在此处输入图片说明

您需要的是将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

这是正确的做法:

<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 使用异步管道订阅 observable,在 *ngIf 中使用它,否则它将尝试迭代尚不存在的内容。 接下来使用 *ngFor 创建多个<li>元素,而不是<ul>

如果您的状态 'user' 切片已规范化并存储为具有 key: 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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM