首页 > 解决方案 > 从 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

标签: angular

解决方案


不要在构造函数中调用任何东西,直到它需要它。只需在方法中调用它。所以当你订阅时,它会自动触发。以下代码应该可以工作。

constructor(public afs:AngularFirestore,db:AngularFirestore) { 
}

getitems(){
     return this.items=this.afs.collection('categories',
            ref=>ref.orderBy('name')).valueChanges() ;
}

推荐阅读