简体   繁体   中英

Firebase - Firestore - Angularfire2 - Angular : How do I access key values within the controller?

I want to convert strings coming from a firestore database key value into a javascript date within an Angular controller after a collection query. I can access values through the template fine but I am not sure how to access values through the controller so I can assign the strings to variables and convert them into a date. Here is my code

export interface Item {
  url: string;
  order: string;
  year: string;
  month: string;
  day: string;
  hour: string;
}

...

export class ItemComponent implements OnInit {
  private itemsCollection: AngularFirestoreCollection<Item>;
  items: Observable<Item[]>;

  constructor(private afs: AngularFirestore) {
    this.itemsCollection = afs.collection<Item>('items', ref => {
      return ref.orderBy('order', 'desc').limit(1);
    });
    this.items = this.itemsCollection.valueChanges();
  }
}

Items is an observable and you can use the built in operators to manipulate it as needed, in this case mapping the values to something else.

this.itemsCollection.valueChanges().pipe(
    map(items => items.map(stringToDateItem))
)

const stringToDateItem = (item: Item) => ({...item, date: new Date(item.year, item.month, item.day)});

In this case we use map twice because first is the map on the observable, stating that we want to change the values when we get them. And since a value is represented by an array we then use map from array to change each individual value to what we need.

Above I've added a new date property to the item so you have to handle that in the interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM