如何在 Angular 中绑定 json 文件中的多个特定值?

How to bind a multiple specific value from json file in Angular?

我正在尝试在 Angular 中执行一个简单的 @input 绑定过程。我做了大部分。我不知道为什么,但我无法获取数据。我认为我的 .map 使用有问题。

这是我的parentcomponent.ts

export class DashboardContainerComponent implements OnInit {   cards: { title: string, body: string }[];

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.http.get("https://jsonplaceholder.typicode.com/comments").subscribe((comments: any) => {
      cts
      // this.cards = comments. ... map? reduce? filter?
      this.cards = comments.map(n => {
        return {title: n["name"], body: n["body"] };
      } )  
    })   }

}

这是childcomponent.ts

export class MyCardComponent implements OnInit {

  @Input() item: {title: string, body: string}[];
  // TODO: define @Input(s) here
  
  constructor() { }

  ngOnInit(): void {
  }

}

这就是我在 parent component.html

中使用此绑定的方式
<div class="dashboard-container">
  <h1>Comments</h1>
  <ng-container *ngIf="!cards">
    <div class="info-text">Cards will appear here.</div> 
  </ng-container>
  
  <ng-container *ngFor="let card of cards">
    <!-- TODO: assign input(s) below in app-my-card -->
    <app-my-card [item]="cards"></app-my-card>
  </ng-container>
</div>

这就是我在 child component.html

中使用此绑定的方式
<div class="card-container">
  <div class="card-title">
    <h1>{{item.title}}</h1>
  </div>
  <div class="card-body">
    <p>{{item.body}}</p>
  </div>
</div>

关于什么是“项目”,模板和 TS 文件之间的子组件存在不一致 您的子组件应该接受一个项目或一组项目,但不能同时接受两者:

  • 调用您传递的子模板 [item]="cards",所以完整数组
  • 在子 .ts 文件中,项目被声明为数组
  • 在子模板文件中,项目应该是一个带有 .title 和 .body 的对象,但它有一个数组(所以未定义)。

这似乎是有道理的: 将输入作为单个元素键入

@Input() item: {title: string, body: string}; // <= no more array

...并将 *ngFor 中定义的元素传递给它(而不是完整数组)

<ng-container *ngFor="let card of cards">
    <!-- TODO: assign input(s) below in app-my-card -->
    <app-my-card 
        [item]="card" // NOT cards 
    ></app-my-card>
  </ng-container>

不要犹豫,通过在您的子模板中添加类似这样的调试内容来了解​​正在发生的事情

<pre>item : {{ item | json }} </pre>