javascript - 迭代按钮点击 Angular 5 上的 api 数据

标签 javascript angular typescript contentful

我有一些从外部 API 调用的数据。现在我想做的是在我的页面上有一个按钮来迭代数据..

所以..例如,假设我的网站上有一个页面,其中有一个标题和一些来自 api 的文本,并且我从 api 收到的数据是

{
    fields: {
        title: 'title 1',
        text: 'this is some text'
    }
},
{
    fields: {
        title: 'title 2',
        text: 'this is some more text'
    }
},

现在我希望将第一个项目插入到标题 div 中,然后将文本插入到文本 div 中

所以像..

<div class="title">{{response.fields.title}}</div>
<div class="text">{{response.fields.text}}</div>

然后,当我单击页面上的 next 按钮时,我希望标题和文本更新为第二项,因此 title 2text 我并不是 100% 会做这样的事情..

所以我的设置如下

contentful.service.ts

@Injectable()
export class ContentfulService {
  private cdaClient = createClient({
    space: CONFIG.space,
    accessToken: CONFIG.accessToken
  });

  constructor() { }

  getProgramItems(query?: object): Promise<Entry<any>[]> {
    return this.cdaClient.getEntries(Object.assign({
      content_type: CONFIG.contentTypeIds.programItems
    }, query))
    .then(res => res.items);
  }

}

app.component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { ContentfulService } from '../contentful.service';
import { Entry } from 'contentful';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
  // define private class properties
  private programItems: Entry<any>[] = [];
  constructor(
    private contentfulService: ContentfulService
  ) { }


  ngOnInit() {
    this.contentfulService.getProgramItems()
      .then(programItems => this.programItems = programItems)
      .then(() => {
        console.log(this.programItems);
      });
  } 

所以基本上我想要每个程序项的标题和文本,以便在单击按钮时更新页面上的标题和文本 div,我考虑过使用 ES6 生成器,但我不确定如何在这个中使用它案例。

如有任何帮助,我们将不胜感激

谢谢

最佳答案

<div class="title">{{currentItem.title}}</div>
<div class="text">{{currentItem.text}}</div>
<button (click)="goToNext()">Next</button>

public counter: number = 0;
public currentItem: Entry<any>;

goToNext() {
    if (this.counter > this.programItems.length) this.counter = this.programItems.length;
    this.currentItem = this.programItems[this.counter];
    this.counter++;
}

你可以尝试上面的方法。

假设您已从服务中获取了 programItems 数组,并且所有内容都已正确填充,那么您可以使用计数器作为数组索引,并在每次单击“下一步”按钮时递增它。

关于javascript - 迭代按钮点击 Angular 5 上的 api 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48697227/

相关文章:

c# - 使用 Javascript 或 C# 验证 Web 表单

css - 尽管其他样式也有效,但无法在 Angular 中使用全局文件中的 SASS 变量

javascript - 输入(类型 ="search")十字图标的 Angular 事件绑定(bind)?

html - 无法解决angular4和html中的文本溢出

javascript - 定义 typescript 类方法

javascript - typescript :有没有办法检查变量是否是具有嵌套属性的接口(interface)定义对象?

javascript - Rails javascript 资源冲突

javascript - 如何在 node.js 中发起 https 请求

javascript - 我的网页在使用 html 和 css 构建的页眉和页脚右侧显示空白

Angular 依赖注入(inject)