Angular Firestore (angularfire2) - 提取所有 "comments" 匹配 "photo" id
Angular Firestore (angularfire2) - Pull all "comments" that match a "photo" id
不知道如何正确 "ask" 这个。我认为在 MySQL 中它被称为 "Joining" 或类似的东西。
我有一个叫 "Photos" 的 collection。我想要添加 "Comments" 到照片的功能。那些 "Comments" 将存储在另一个 collection 中。评论的结构如下:
- 评论(字符串)
- 日期(字符串 - 发布时间)
- photoId(此评论所属照片的 ID)。
我有一个 Angular 页面已经在显示有关照片的信息。现在我想显示那张照片的评论。我怎样才能只提取属于那张照片的评论??
此外,我希望它是异步的,因为我将能够添加新评论 "on the fly"。
非常感谢!
您可以像这样查询您的 comments
集合:
...
constructor(private afs: AngularFirestore) {
afs.collection('comments', ref => ref.where('photoId','==', this.idOfPhotoYouAreDisplaying)).valueChanges()
}
...
如果您想在模板中检查 null
,您可以将结果分配给一个变量(例如 comments
):
comments: Comment[];
comments$: Observable<Comment[]>;
constructor(private db: AngularFirestore) {
this.comments$ = this.db.collection(config.collection_comments, ref => ref.where('photoId', '==', this.photoId))
.snapshotChanges()
.pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Comment;
const id = a.payload.doc.id;
return { id, ...data };
});
}));
}
ngOnInit() {
this.comments$.subscribe(c => this.comments == c);
}
现在在您的模板中,您可以查看 comments
:
<div *ngIf="comments">
<div *ngFor="let comment of comments">
...
</div>
</div>
注1:
您不必将其分配给变量。您可以检查 ngIf
中的 async
管道,但是当您循环评论时,再次使用 async
创建第二个订阅,这将导致您的查询执行两次。
注二:
使用 async
管道处理您的可观察对象的取消订阅。订阅组件时,您需要自己处理。 (有多种方法)
不知道如何正确 "ask" 这个。我认为在 MySQL 中它被称为 "Joining" 或类似的东西。
我有一个叫 "Photos" 的 collection。我想要添加 "Comments" 到照片的功能。那些 "Comments" 将存储在另一个 collection 中。评论的结构如下:
- 评论(字符串)
- 日期(字符串 - 发布时间)
- photoId(此评论所属照片的 ID)。
我有一个 Angular 页面已经在显示有关照片的信息。现在我想显示那张照片的评论。我怎样才能只提取属于那张照片的评论??
此外,我希望它是异步的,因为我将能够添加新评论 "on the fly"。
非常感谢!
您可以像这样查询您的 comments
集合:
...
constructor(private afs: AngularFirestore) {
afs.collection('comments', ref => ref.where('photoId','==', this.idOfPhotoYouAreDisplaying)).valueChanges()
}
...
如果您想在模板中检查 null
,您可以将结果分配给一个变量(例如 comments
):
comments: Comment[];
comments$: Observable<Comment[]>;
constructor(private db: AngularFirestore) {
this.comments$ = this.db.collection(config.collection_comments, ref => ref.where('photoId', '==', this.photoId))
.snapshotChanges()
.pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Comment;
const id = a.payload.doc.id;
return { id, ...data };
});
}));
}
ngOnInit() {
this.comments$.subscribe(c => this.comments == c);
}
现在在您的模板中,您可以查看 comments
:
<div *ngIf="comments">
<div *ngFor="let comment of comments">
...
</div>
</div>
注1:
您不必将其分配给变量。您可以检查 ngIf
中的 async
管道,但是当您循环评论时,再次使用 async
创建第二个订阅,这将导致您的查询执行两次。
注二:
使用 async
管道处理您的可观察对象的取消订阅。订阅组件时,您需要自己处理。 (有多种方法)