我正在通过json检索http.get数据,我的问题是我无法在typescript中获取我的密钥的具体值。
我返回的数据格式为(json):
[
{
"id": 1,
"name": "Albany",
"manufacture": "Albany Superior Low Gi Sliced Brown Seed Bread 700g",
"price": 15.49,
"category": "Food",
"type": "Breads",
"image": "data:image/jpeg;base64,/9j/4AAQSkZJ..."
},
{
"id": 2,
"name": "Blue Ribbon",
"manufacture": "Blue Ribbon Brown Plus Low Gi Bread 700g",
"price": 13.99,
"category": "Food",
"type": "Breads",
"image": "data:image/jpeg;base64,/9j/4AAQSkZJRg..."
}
]
在Angular中,我的服务如下:
export class ProductService {
prodType:ProductModel;
productList:object;
prodList: Array<ProductModel> = [];
prodMap: Map<number, ProductModel>;
constructor( private http: HttpClient ) { }
getAllProducts(): Array<ProductModel>{
this.http.get<Array<ProductModel>>('/product/service/send/all/products').subscribe(
data => {
console.log( data );
},
error => {
console.error("HTTP FAILURE ERROR!!!");
}
);
return this.prodList;
}
getProductByType( productSearch:string ){
this.productList = this.prodList.find( x=> x.getType() == productSearch);
console.log( this.productList);
}
}
ProductModel如下:
export class ProductModel {
private id: number;
private name: string;
private manufacture: string;
private price: number;
private category: string;
private type: string;
private image: string;
// get and setters
百万美元的问题;假设我想在我的数据中搜索产品类型,并且只想从我的json数据中使用类型牛奶来控制日志产品。
我该怎么做?我已经搜索了类似的解决方案,但它们没有用。
答案 0 :(得分:1)
首先将HTTP结果分配给您的类成员,然后过滤您的数据,然后console.log过滤的数组项。
export class ProductService {
prodType:ProductModel;
productList:object;
prodList: Array<ProductModel> = [];
prodMap: Map<number, ProductModel>;
constructor( private http: HttpClient ) { }
getAllProducts() {
this.http.get<Array<ProductModel>>('/product/service/send/all/products').subscribe(
datas => {
this.prodList = datas;
},
error => {
console.error("HTTP FAILURE ERROR!!!");
}
);
}
getProductByType( productSearch:string ): Array<ProductModel>{
let filteredProducts:Array<ProductModel> = this.prodList.filter(product => product.type == productSearch);
filteredProducts.forEach(product=> console.log(product);
return filteredProducts;
}
}
答案 1 :(得分:0)
您可以添加地图并修改来自http get调用的响应,并在将其分配给列表之前对其进行过滤。如果你想将它们分开,那么你需要将逻辑分成两个方法,一个用来获取香草列表,然后在它上面过滤数据
getAllProducts(): Array<ProductModel>{
return this.http.get<Array<ProductModel>>('/product/service/send/all/products').map(data => data.filter(value => value.type == 'milk')).subscribe() ;
}