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