我正在使用angularfire。 当我第一次获得数据时它工作正常并显示数据但是当我导航到另一个页面然后再回到相同时,数据会丢失,除非我在firebase数据库或重新加载页面中更改了某些内容。
那么,我做错了什么?
任何帮助都是合情合理的。
这是我的检索数据服务:
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import { Band } from '../models/Band';
@Injectable()
export class UserBandsService {
userBandCollection: AngularFirestoreCollection<Band>
bands: Observable<Band[]>
constructor(
public afs: AngularFirestore,
) {
this.userBandCollection = this.afs.collection('bands', ref => ref.where(
'users.userRef', '==', 'k9JEqf4JhggNAeVT1POoN0nJC0u2'
)
);
this.bands = this.userBandCollection.snapshotChanges().map(changes => {
return changes.map( a => {
const data = a.payload.doc.data() as Band;
data.id = a.payload.doc.id;
return data;
});
});
}
getBands(){
return this.bands;
}
}
还有component.ts
import { Component, OnInit } from '@angular/core';
import { UserBandsService } from '../core/user-bands.service';
import { Band } from '../models/Band';
@Component({
selector: 'app-user-bands',
templateUrl: './user-bands.component.html',
styleUrls: ['./user-bands.component.css']
})
export class UserBandsComponent implements OnInit {
userBands: Band[];
constructor(
private bandsService: UserBandsService,
) {}
ngOnInit() {
this.bandsService.getBands().subscribe(userBands => {
if(userBands){
this.userBands = userBands;
}
});
}
}
模板:
<div *ngFor="let band of userBands">
{{band.estilo}}
</div>