首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从API调用循环的角4

从API调用循环的角4
EN

Stack Overflow用户
提问于 2018-04-25 08:45:56
回答 1查看 2.2K关注 0票数 0

我需要一些帮助。我做了一个HTTP调用,它可以工作。我从API调用中得到了一个产品列表,但现在我需要遍历它们,以便选择它们的“名称”。

这就是我的Product.Service.TS的样子:

代码语言:javascript
复制
import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import { KioskService } from "./kiosk.service";
import { Object } from "../object";

@Injectable()
export class ProductService {
  private config: Object = {};
  public domainSettings: Object = {};

  constructor(private http: Http, private kioskservice: KioskService) {}

  public getAllProducts() {
    return new Promise((resolve, reject) => {
      this.http
        .get(
          `${this.kioskservice.getAPIUrl()}products/?apikey=${this.kioskservice.getAPIKey()}`
        )
        .toPromise()
        .then(
          res => {
            this.config = res.json();
            console.log(res.json());
            resolve();
          },
          msg => {
            throw new Error("Couldn't get all Bookings: " + msg);
          }
        );
    });
  }
}

它展示了所有的产品,所以40个对象:

如何循环遍历所有对象,以便选择如下示例所示的“名称”:

代码语言:javascript
复制
public LocationGUID() {
    return this.config["LocationGuid"];
}

上面的示例将从对象返回"LocationGuid“。这很容易,因为只有一个对象被返回,但是现在我需要40个对象!谁来帮忙:D

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-25 08:58:42

在下决心之前循环通过。但我不确定这是否是你真正想要达到的最干净的解决方案。

代码语言:javascript
复制
import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import { KioskService } from "./kiosk.service";
import { Object } from "../object";

@Injectable()
export class ProductService {
    private config: Object = {};
    // CHANGE (names are added in this array)
    private names: Object = [];
    public domainSettings: Object = {};

    constructor(private http: Http, private kioskservice: KioskService) {}

    public getAllProducts() {
        return new Promise((resolve, reject) => {
        this.http
            .get(
            `${this.kioskservice.getAPIUrl()}products/?apikey=${this.kioskservice.getAPIKey()}`
            )
            .toPromise()
            .then(
            res => {
                this.config = res.json();
                console.log(res.json());
                // CHANGE (add names)
                if (this.config && this.config.length) {
                    this.names = [];
                    for (let i = 0; i < this.config.length; i++) {
                        this.names.push(this.config[i]['Name']);
                    }
                }
                resolve();
            },
            msg => {
                throw new Error("Couldn't get all Bookings: " + msg);
            }
            );
        });
    }

    // CHANGE (function to fetch the names)
    public getNames() {
        return this.names;
    } 
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50017811

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档