angular - 从 Cloud Firestore 获取数据并渲染到 html 组件中
问题描述
我正在从我的云 Firestore 中获取数据并在我的 html 组件中呈现。在我第一次尝试使用该组件时,我看到我的数据呈现为 html 组件
.component.ts 文件
import { Component, OnInit, ViewChild } from '@angular/core';
import { ItemsService } from 'src/app/services/items.service';
import { NgForm } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { ProductsService } from 'src/app/services/products.service';
import { Product } from 'src/app/modals/products.modal';
@Component({
selector: 'app-admin-new',
templateUrl: './admin-new.component.html',
styleUrls: ['./admin-new.component.scss']
})
export class AdminNewComponent implements OnInit {
@ViewChild('f') form:NgForm
categories
default="Bread"
constructor(public iservice:ItemsService,private
prservice:ProductsService,private router:Router,private
route:ActivatedRoute) { }
ngOnInit() {
this.iservice.getitems().subscribe(items=>{
console.log(items) //this is the data fetched from firestore
this.categories=items
})
}
onsubmit(f){
this.prservice.fetchintocardcomponent(f)
this.router.navigate(['admin/products'])
}
}
服务文件
import { Injectable } from '@angular/core';
import
{AngularFirestoreDocument,AngularFirestore,AngularFirestoreCollection}
from 'angularfire2/firestore';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ItemsService {
itemscollection:AngularFirestoreCollection<any>
items:Observable<any[]>
constructor(public afs:AngularFirestore,db:AngularFirestore) {
this.items=this.afs.collection('categories',ref=>ref.orderBy('name'))
.valueChanges()
}
getitems(){
return this.items
}
}
现在我将它呈现在 html 组件中
<select [ngModel]="default" class="browser-default custom-select"
id="category"
ngModel name="select" required #select="ngModel"
>
<option *ngFor="let c of categories" value="{{c.name}}">{{c.name}} .
</option>
</select>
所以这是我得到的截图,它工作正常 https://ibb.co/PFW6sR9
但是在提交表单后,当我转到另一个组件时
this.router.navigate(['admin/products'])
然后当我返回同一个组件时,我看不到从 firestore 获取的值在 html 组件中呈现
这是我的问题的屏幕截图 https://ibb.co/j5yNChs
解决方案
不要在构造函数中调用任何东西,直到它需要它。只需在方法中调用它。所以当你订阅时,它会自动触发。以下代码应该可以工作。
constructor(public afs:AngularFirestore,db:AngularFirestore) {
}
getitems(){
return this.items=this.afs.collection('categories',
ref=>ref.orderBy('name')).valueChanges() ;
}
推荐阅读
- java - 为什么在使用相同 AWS Lambda 函数的多个触发器将数据从 Mysql 迁移到 S3 时数据会重复
- azure - 需要帮助设置 Azure DevOps
- r - 使用 DT 包根据列值对两列进行条件格式
- python - 使用python中的用户输入值按列过滤数据
- javascript - 为什么 Promise.then() 只适用于箭头函数?
- php - 检查当月是否已有记录
- artifactory - jFrog 存储库上的 helm 图表 index.yaml 的 URL 错误(本地://.. 而不是 https://..)
- javascript - 在反应中观察变量的变化
- html - 悬停在一个链接上更改链接本身和另一个链接的颜色(反之亦然)
- python - 为什么我的卡尔曼滤波器的测量和估计是相同的?