在收集查询后,我想在Angular控制器中将来自Firestore数据库键值的字符串转换为javascript日期。我可以通过模板访问值,但是我不确定如何通过控制器访问值,因此可以将字符串分配给变量并将其转换为日期。这是我的代码
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();
}
}
答案 0 :(得分:0)
Items是可观察的,您可以根据需要使用内置的运算符对其进行操作,在这种情况下,将值映射到其他对象。
this.itemsCollection.valueChanges().pipe(
map(items => items.map(stringToDateItem))
)
const stringToDateItem = (item: Item) => ({...item, date: new Date(item.year, item.month, item.day)});
在这种情况下,我们使用map两次,因为首先是可观察对象上的map,表明我们想在获取值时更改其值。而且,由于值是由数组表示的,因此我们可以使用数组中的map将每个单独的值更改为所需的值。
在上面,我已经向项目添加了一个新的 date 属性,因此您必须在界面中进行处理。