製品のリストを含むjsonファイルがあります。
[{"id":76,
"name":"A",
"description":"abc",
"price":199,
"imageUrl":"image.jpg",
"productCategory":[{
"categoryId":5,
"category":null
},{
"categoryId":6,
"category":null
}
]}
次に、次のようなカテゴリのリストを含む2番目のjsonファイルがあります。
[{"id":5,"name":"red"},
{"id":6,"name”:"blue"}]
Angularでこの2つのjsonファイルのカテゴリに参加するための最良の方法は何ですか?これが私が達成しようとしていることです。
[{"id":76,
"name":"A",
"description":"abc",
"price":199,
"imageUrl":"image.jpg",
"productCategory":[{
"categoryId":5,
"category":red
},{
"categoryId":6,
"category":blue
}
]}
サービスを使用してデータを取得するstackblitzを作成します。はい、方法はswitchMapとmapを使用することです。SwitchMapは配列を受け取り、observableを返す必要があります。マップを使用して、受信したデータを変換し、変換したデータを返します
this.dataService.getCategories().pipe(
//first get the categories, the categories is in the
//variable cats
switchMap((cats:any[])=>{
return this.dataService.getProducts().pipe(map((res:any[])=>{
res.forEach(p=>{ //with each product
p.productCategory.forEach(c=>{ //with each productCategory in product
//equals a propertie "category" to the propertie "name" of the cats
c.category=cats.find(x=>x.id==c.categoryId).name
})
})
return res
}))
})).subscribe(res=>{
console.log(res)
})
ユニークな商品しか作れないのなら
this.dataService.getCategories().pipe(
switchMap((cats:any[])=>{
return this.dataService.getUniqProduct(2).pipe(map((res:any)=>{
res.productCategory.forEach(c=>{
c.category=cats.find(x=>x.id==c.categoryId).name
})
return res
}))
})).subscribe(res=>{
console.log(res)
})
カテゴリを「キャッシュ」したdataServiceを改善できます
getCategories() {
if (this.categories)
return of(this.categories);
return http.get(......).pipe(tap(res=>{
this.categories=res;
}))
}
注:スタックビットでは、「of」を使用してhttp.get(...)への呼び出しをシミュレートします。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加