我正在从云存储中获取数据并在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
答案 0 :(得分:0)
不要在构造函数中调用任何东西,直到需要它为止。只需在方法内部调用即可。因此,当您订阅时,它将自动触发。下面的代码应该工作。
constructor(public afs:AngularFirestore,db:AngularFirestore) {
}
getitems(){
return this.items=this.afs.collection('categories',
ref=>ref.orderBy('name')).valueChanges() ;
}