问题
I'm trying to get id of the collection to use it in the ionic page:
this is my interface:
export interface Item {
categoryOfPost: string;
imageUrl: string;
nameOfPost: string;
cityOfPost: string;
createdDate: string;
currencyOfPost: string;
priceOfPost: number;
typeOfPost: number;
statusOfPost: string;
id?: string;
}
private itemsCollection: AngularFirestoreCollection<Item>;
items: Observable<Item[]>;
and this is the content of the getPosts function
this.itemsCollection = this.afs.collection('posts', ref => ref.orderBy('createdDate', 'desc'));
this.items = this.itemsCollection.valueChanges();
when i want to view the content i use:
<ion-card style="margin-bottom: 25px; background-color: burlywood" *ngFor="let item of items | async">
<ion-item text-wrap style="margin-bottom: 25px; background-color: burlywood">
<ion-list >
<ion-item>
<img src="{{ item.imageUrl }}">
cityOfPost: {{ item.id }}
<button ion-button (click)="detailpage(item.id)">click to test </button>
</ion-item>
</ion-list>
</ion-item>
</ion-card>
I can show everything on the HTML EXCEPT for the ID it comes UNDEFINED ???? what is the correct way to display it ???
Thank you.
回答1:
This is because by using valueChanges()
"all Snapshot metadata is stripped and just the method provides only the data", as explained in the doc.
You should use snapshotChanges()
, see the doc here which says: "Why would you use it? - When you need a list of data but also want to keep around metadata."
回答2:
i changed the code to:
this.itemsCollection = this.afs.collection('posts', ref => ref.orderBy('createdDate', 'desc'));
this.items = this.itemsCollection.snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data() as Item;
const id = a.payload.doc.id;
return { id, ...data };
}))
);
and it worked perfectly.
来源:https://stackoverflow.com/questions/53168962/get-the-id-of-collection-document-from-firestore-using-angularfire2-in-ionic-3