【发布时间】:2020-10-14 03:22:54
【问题描述】:
我正在使用 Angular Firestore 从 Firebase 数据库中提取图像引用。我知道如何从数据库中获取 observable 并通过异步将其挂接到模板中,但我想将数据公开给我的组件以读取 Oninit()。我尝试了多种方法来拖出数据,但都没有成功。下面的代码 Spinets
product.model.ts
export interface Product {
$key?: string;
name?: string;
price?: number;
condition?: string;
image?: string;
mainPic?: string;
}
product.component.ts
Variables-----
product: Observable<Product>;
Constructor----
----One of the ways I got the firebase document
this.invoicesCollection = this.afs.collection("/Products");
this.product = this.getProduct2("test_product");
---Another way I got the firestore document
this.TED = this.db.getDoc3().subscribe((doc) => this.TED = doc as Product);
-- this is inside a service
getDoc3() {
const ref = this.afs.collection("/Products").doc("test_product");
// return ref.get().subscribe((doc) => this.data = doc as Product);
return ref.get()
}
-- yet another way I got the data
getProduct2(id: string): Observable<Product> {
// const productsDocuments = this.afs.doc<Product>("Products/" + id);
const productsDocuments = this.afs.doc<Product>("Products/test_product");
return productsDocuments.snapshotChanges().pipe(
map((changes) => {
const data = changes.payload.data();
const id = changes.payload.id;
return { id, ...data as Product };
})
);
}
所有这些方法都可用于检索 observable,但我无法访问组件中的数据。
我尝试将数据拖出可观察对象
// console.log(JSON.stringify(this.product as Product))
//console.log(JSON.parse(JSON.stringify(this.product)))
// this.productsService.getProducts().subscribe((data) => {
// this.products = data.map((e) => {
// return {
// id: e.payload.doc.id,
// ...e.payload.doc.data(),
// } as Product;
// });
// getInvoice() {
// var docref = this.afs.collection("/Products").doc(this.invoiceId);
// var docref = this.afs.collection("/Products").doc("test");
// docref.ref.get().then((doc) => {
// if (doc.exists) {
// var invoice = doc.data(); // <------WORKS
// this.invoice = doc.data(); <------DOESN'T WORK
// console.log("Invoice data: ", doc.data());
// } else {
// console.error("No matching invoice found");
// }
// });
// }
我试图传递我的数据的地方
this.galleryImages = [
{
small: this.product.image,
medium: this.product.image,
big: this.product.image,
},
NGX 图片库
<div>
<div class="Home">
<div class="content">
<ngx-gallery [options]="galleryOptions" [images]="galleryImages"></ngx-gallery>
</div>
</div>
</div>
任何帮助将不胜感激。谢谢你。如果您需要更多代码或说明,请告诉我。
【问题讨论】:
-
为什么需要模板外的数据?
-
我正在尝试将图像引用传递给 ngx 库。
this.galleryOptions = [ this.galleryImages = [ { small: this.product.image, medium: this.product.image, big: this.product.image, }, -
模板中是否使用了
this.galleryImages?可以发一下吗? -
我更新了帖子以包含画廊的 html
标签: json angular typescript firebase observable