我正在使用
我正在做什么
我点击了收藏列表中的项目
此项目链接到文档视图
我显示文件
我需要更新返回的日期,而不是使用 valueChanges()。
我使用 snapshotChanges()
问题
这大部分工作正常,并返回数据,我已正确格式化返回的日期
但是,控制台打印文档5次
问题
非常感谢任何帮助! :)
组件TS
import { Component, OnInit } from '@angular/core';
// Firestore
import { Observable } from 'rxjs/Observable';
import { AngularFirestore, AngularFirestoreDocument } from 'angularfire2/firestore';
// Routes
import { Router, ActivatedRoute } from '@angular/router';
// Moment JS
declare var moment: any;
@Component({
selector: 'app-albums-detail',
templateUrl: './albums-detail.component.html',
styleUrls: ['./albums-detail.component.css']
})
export class albumsDetailComponent implements OnInit {
folderId: string;
albumId: string;
private albumDoc: AngularFirestoreDocument<any>;
album: Observable<any>;
constructor(
private readonly afs: AngularFirestore,
private activatedRoute: ActivatedRoute,
private router: Router) { }
ngOnInit() {
// Look at the url for the Folder and album ID and set the local variable
this.activatedRoute.params.forEach((urlParameters) => {
this.folderId = urlParameters['folderId'];
this.albumId = urlParameters['albumId'];
});
// Return the albums list
this.getalbumData();
}
getalbumData() {
this.albumDoc = this.afs.doc(`folders/${this.folderId}/albums/${this.albumId}`);
//this.album = this.albumDoc.valueChanges();
this.album = this.albumDoc.snapshotChanges().map(action => {
const id = action.payload.id;
const data = action.payload.data();
// Get the date from each album
var albumDateTimestamp = data.album_date;
// Convert the unix value and format it based on the users locale setting
var albumDateISO = moment(albumDateTimestamp).format("DD/MM/YYYY");
// Create a new 'name' to use in the HTML binding
data.formattedDate = albumDateISO;
console.log(data);
return { id, ...data };
});
}
}
&#13;
组件HTML
<h1> {{ (album | async)?.album_title }} </h1>
<div>
{{ (album | async)?.album_title }}
{{ (album | async)?.formattedDate }}
{{ (album | async)?.album_client }}
{{ (album | async)?.album_reference }}
</div>
&#13;
更新
我已经在几个地方问了这个问题并且发了几个人没有太多运气,所以我尝试了一种新的方法。我不完全确定它干净,但它确实有效。它不再使用AngularFire,因为我无法解释为什么它会多次打印到控制台。我直接从firestore文档中举了一个例子。我有一堆全局变量,我在抓取数据后将其更新并用于我的数据绑定。感觉就像每次加载页面时它都在提取/读取数据。有没有办法检查?
如果有人能告诉我这是否是执行此操作的合法方式,那就太棒了:D
getProjectData() {
var db = firebase.firestore();
var docRef = db.collection(`folders/${this.folderId}/albums`).doc(`${this.albumId}`);
docRef.get().then((doc) => {
if (doc.exists) {
console.log("Document data:", doc.data());
var data = doc.data();
var id = doc.id;
this.shazam(data, id);
} else {
console.log("No Such Document");
}
});
}
shazam(data, id) {
var albumTimeStamp = data.album_date;
// Convert the unix value and format it based on the users locale setting
var albumDateIso = moment(albumTimeStamp).format("DD/MM/YYYY");
// Create a new 'name' to use in the HTML binding
data.formattedDate = albumDateIso;
this.albumTitle = data.project_title;
this.albumDate = data.formattedDate;
}
&#13;
答案 0 :(得分:0)
您还可以向ngOnInit
添加一条日志语句吗?我的最佳猜测是该组件被多次初始化。