我需要帮助。 我做了一个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"];
}
上面的示例将从Object返回“LocationGuid”。这很简单,因为只返回了1个Object,但现在我需要40个对象! 有人请帮忙:D
答案 0 :(得分:0)
在解决之前循环。但我不确定这是你真正想要实现的最干净的解决方案。
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;
}
}