Firebase - Firestore - Angularfire2 - Angular:如何访问控制器中的键值?
Firebase - Firestore - Angularfire2 - Angular : How do I access key values within the controller?
我想在收集查询后将来自 firestore 数据库键值的字符串转换为 Angular 控制器中的 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();
}
}
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,因为第一次是 observable 上的 map,表明我们想要在获取值时更改它们。由于值由数组表示,因此我们使用数组中的映射将每个单独的值更改为我们需要的值。
上面我为项目添加了一个新的 日期 属性,因此您必须在界面中处理它。
我想在收集查询后将来自 firestore 数据库键值的字符串转换为 Angular 控制器中的 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();
}
}
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,因为第一次是 observable 上的 map,表明我们想要在获取值时更改它们。由于值由数组表示,因此我们使用数组中的映射将每个单独的值更改为我们需要的值。
上面我为项目添加了一个新的 日期 属性,因此您必须在界面中处理它。