简体   繁体   English

如何使用 Angular 中的 API 数据动态创建按钮?

[英]How can I dynamically create buttons with the data of an API in Angular?

I started to create buttons and grids with given data.我开始用给定的数据创建按钮和网格。 For that purpose I created an array with objects in it.为此,我创建了一个包含对象的数组。 With the data in the array I create button and grids dynamically but now I want to do the same but instead of using a local variable to build the grids I want to create them with given data by an API.使用数组中的数据,我动态创建按钮和网格,但现在我想做同样的事情,但不是使用局部变量来构建网格,我想通过 API 使用给定数据创建它们。 My problem is that it return an Observable and not an array.我的问题是它返回一个 Observable 而不是数组。 I tried to transform the data and push it into an array but I get always errors.我试图转换数据并将其推送到数组中,但我总是遇到错误。

I tried to use the take and tap operator but everything is crashing always.我尝试使用 take and tap 操作符,但一切总是崩溃。 I cannot transform the data as I want such that it works again.我无法根据需要转换数据以使其再次工作。

In app.component.ts在 app.component.ts

// I have to change this.gridService.items somehow that it fits with an API
  ngOnInit(): void {
    this.gridItems = this.gridService.items;
  }

In grid.service.ts the private variable _items should be replaced with an API-Call which returns the same data structure and content but it would be an Observable -- and there is where to problem begins...在 grid.service.ts 中,私有变量 _items 应该替换为一个 API-Call,它返回相同的数据结构和内容,但它是一个 Observable —— 问题从哪里开始......

Can anyone edit my project with some dummy code how it could possibly work, so I understand the logic?任何人都可以用一些虚拟代码编辑我的项目,它是如何工作的,所以我理解逻辑?

I really would appreciate your help.我真的很感激你的帮助。

If any information is missing, please tell me!如果缺少任何信息,请告诉我! Thank you!谢谢!

Use async pipe on your observable result:在可观察结果上使用异步管道:

<div *ngFor="let item of items$ | async">{{ item | json }}</div>

$ on end of variable is convention for variable containing streamed data in case of angular observables.变量末尾的$是在角度观察的情况下包含流数据的变量的约定。

Cara!卡拉! Thank you for the question.感谢你的提问。 If I understood you correctly, you want to replace your this.gridItems = this.gridService.items;如果我理解正确,你想替换你的this.gridItems = this.gridService.items; to the HTTP call.到 HTTP 调用。

I've prepared a stackblitz example with emulation of an API call.我准备了一个模拟 API 调用的stackblitz示例。

My main idea is the usage of $async pipe with Observable<GridItem[]> instead of sync getting.我的主要想法是使用$async管道和Observable<GridItem[]>而不是同步获取。 Don't forget to handle errors from an API.不要忘记处理来自 API 的错误。

PS I'm waiting for your feedback. PS 我正在等待您的反馈。

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

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