当用户更新您的个人资料照片时,我需要将他的照片上传到Firebase存储并立即检索下载网址以更新其个人资料集。
在另一种情况下,当用户更新他的个人资料时,他不会更改他的个人资料图片,因此我没有imageData也不需要上传他的照片,只需更新他的个人资料信息
我的saveProfile()
方法:
if (this.profileForm.valid) {
....
//Check if the user change his picture. If yes, the userProfilePicture has data.
If (userProfilePicture) {
//upload the picture to firestorage
const path = `/profile/${this.profile.id}.jpg`;
const task = this.afStorage
.ref(path)
.putString(imageData, 'base64', { contentType: 'image/jpeg' });
// subscribe to download url
task.downloadURL().subscribe(
url => {
//updating profileUrl in the form
this.profileForm.patchValue({ avatar: url });
//Doing the update in Firestore
this.afs.doc(`/profile/${id}`).update(this.profileForm.value);
});
}
Else {
// just update the profile information
this.afs.doc(`/profile/${id}`).update(this.profileForm.value);
}
}
我想避免在2个地方复制更新代码。有没有更方便的方法来实现这一目标? 也许如果有一种方法可以在我有downloadUrl(在2个场景中)可用时进行更新:
If (userProfilePicture) {
//upload the picture
//subscribe to get the download url
}
//AWAIT for the subscribe to return the download URL and when the download URL is available then update
?? How to do this
//update the profile information with the new or existent download URL
await??? this.afs.doc(`/profile/${id}`).update(this.profileForm.value);
答案 0 :(得分:1)
任务的FYI downloadURL()
在5.0中折旧,您需要在上传完成后使用ref上的那个;所以你需要保持对它的引用:
const path = `/profile/${this.profile.id}.jpg`;
const ref = this.afStorage.ref(path);
const task = ref.putString(imageData, 'base64', { contentType: 'image/jpeg' });
task.snapshotChanges().pipe(
filter(snap => snap.state === storage.TaskState.SUCCESS)
switchMap(() => ref.getDownloadURL())
).subscribe(url => {
...
})
至于减少重复代码,只需使用更新即可;因为这只会更新指定的字段。只需将个人资料图片从profileForm中删除。
// if there's a profile picture to upload, do so
if (userProfilePicture) {
const path = `/profile/${this.profile.id}.jpg`;
const ref = this.afStorage.ref(path);
const task = ref.putString(imageData, 'base64', { contentType: 'image/jpeg' });
task.snapshotChanges().pipe(
filter(snap => snap.state === storage.TaskState.SUCCESS)
switchMap(() => ref.getDownloadURL())
).subscribe(profilePicture => {
this.afs.doc(`/profile/${id}`).update({profilePicture});
})
}
// also just update the rest of the profile, update is non-destructive and only overwrites the fields specified
this.afs.doc(`/profile/${id}`).update(this.profileForm.value);