我需要一些帮助。我做了一个HTTP调用,它可以工作。我从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“。这很容易,因为只有一个对象被返回,但是现在我需要40个对象!谁来帮忙:D
发布于 2018-04-25 08:58:42
在下决心之前循环通过。但我不确定这是否是你真正想要达到的最干净的解决方案。
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;
}
}https://stackoverflow.com/questions/50017811
复制相似问题