【问题标题】:Angular 4 For loop from API call来自API调用的Angular 4 For循环
【发布时间】:2018-04-25 17:14:05
【问题描述】:

我需要帮助。 我进行了 HTTP API 调用,它可以工作。我从 API 调用中获取了产品列表,但现在我需要遍历它们,以便我可以选择它们的“名称”。

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

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 个对象:

我怎样才能遍历所有对象,以便我可以像这个例子一样选择“名称”:

public LocationGUID() {
    return this.config["LocationGuid"];
}

上面的示例将从对象返回“LocationGuid”。这很容易,因为只返回 1 个对象,但现在我需要 40 个对象! 有人请帮忙:D

【问题讨论】:

  • 您是否尝试使用 *ngFor 指令循环遍历您的数组?
  • 嗨@faizan,我试过了,但我不能让它正常工作。你能告诉我如何在我的情况下正确使用 *ngFor 指令吗?
  • 您还需要共享 HTML,通常我们可以 *ngFor 在 DOM 元素上类似这样。 *ngFor="let value of values" 并且在元素内部,我们可以使用插值作为 {{value.name}} 访问值,如果可能的话,将您的代码上传到 stackblitz
  • 在使用 *ngFor 处理数据时,您可能必须使用 async 管道,例如 <div *ngFor="let c of config | async">{{ c?.LocationGuid }}</div>
  • 您能多描述一下您想要实现的目标吗?我发布了一个答案,但没有更多信息很难猜测代码是否有意义......

标签: angular api typescript http


【解决方案1】:

在解析之前循环遍历。但我不确定这是否是您真正想要实现的最干净的解决方案。

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;
    } 
}

【讨论】:

  • 嗨 Manuel,我想要实现的是循环思考每个对象并从中获取“名称”并将其保存在一个函数中。像 public LocationGUID() { return this.config["LocationGuid"]; }
  • 您为我编写的代码有效。我可以 console.log(this.names) 它会显示所有 40 个产品的名称!!
  • 但是我怎样才能将它保存在像 LocationGuid 这样的函数中
  • @MexLataster 我更新了我的答案。 1.我仍然不确定这是干净的代码。 2.如果它帮助您实现了您的愿望,请不要忘记接受答案。
  • @ManuelManhart 如果你想让它更干净,第一件显而易见的事情就是删除对new Promise()resolve() 的冗余调用:this.http().toPromise().then(...) 链已经是一个承诺,所以代码可以返回那个值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-06
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 2010-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多