问题
hello guys i have a problem to format my firebase-data into array
this is my service where im retrieving data from firebase
filename: subcategory.service.ts
export class SubcategoryService {
subcategoryRef: AngularFireList<any> = null;
constructor(private db: AngularFireDatabase) {
this.subcategoryRef = db.list("/subCategory");
}
getSubCategoriesById(inp_subCatid: string): Observable<any[]> {
return this.subcategoryRef.snapshotChanges().pipe(
take(1),
map(changes => changes.map(c =>
({ key: c.payload.key, ...c.payload.val() })
).filter((subCat) =>
subCat.catid === inp_subCatid
)
));
}
}
im calling the function getSubCategoriesById() in the following file
filename: subcategory.page.ts
this.SubcategoryService.getSubCategoriesById("cat01")
.subscribe(subCategories =>
this.subCat = Object.values(subCategories)
)
the structure of the object what im retrieving looks like this
there is an array in which there is one object in which my destination objects are
but i would like to format the data as the following structure
[
alcoholic:{
active:true,
ageRating: true,
catgeory: "cat01"
...
},
warmdrinks:{
active:true,
ageRating: false,
catgeory: "cat01"
...
},
softdrinks:{
active:true,
ageRating: false,
catgeory: "cat01"
...
},
]
so that i have an array with 3 objects inside.
my firebase database for this case looks like this
hope someone can help me, if someone needs more information, please let me know
回答1:
I think you should use valueChanges rather than snapshotChanges()
return this.getSubCategoriesList().snapshotChanges().pipe(
to
return this.getSubCategoriesList().valueChanges().pipe(
valueChanges returns an Observable of document data. The metadata is stripped off.
I am assuming you are using Angularfire...
回答2:
You can add a map to the chain on the last array map to pickup the attributes you want:
getSubCategoriesById(inp_subCatid: string): Observable<any[]> {
return this.subcategoryRef.snapshotChanges().pipe(
take(1),
map(changes => changes.map(c =>
({ key: c.payload.key, ...c.payload.val() })
).filter((subCat) =>
subCat.catid === inp_subCatid
).map(({alcoholic,softdrinks,warmdrinks,...rest}) => ({
alcoholic,softdrinks,warmdrinks
})
));
}
来源:https://stackoverflow.com/questions/61567837/angular-firebase-format-retrieved-data-from-firebase-into-array