【发布时间】: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);
}
);
});
}
}
我怎样才能遍历所有对象,以便我可以像这个例子一样选择“名称”:
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