Skip to content

Instantly share code, notes, and snippets.

@joel-daros
Last active June 4, 2018 19:44
Show Gist options
  • Save joel-daros/ac0e6d7eaa403542bb757152a617b3b5 to your computer and use it in GitHub Desktop.
Save joel-daros/ac0e6d7eaa403542bb757152a617b3b5 to your computer and use it in GitHub Desktop.
[Angularfire] Upload the profile picture to Firestorage and then update user with downloadUrl
public cameraAvatar: string; //base64 image data get from camera
public profileForm: FormGroup; // reactive form data
saveProfile() {
if (this.profileForm.valid) {
let loader = this.loadingCtrl.create();
loader.present();
let toast = this.toastCtrl.create({
message: 'Data saved successfully',
duration: 3000
});
const path = `/profile/${this.profile.id}.jpg`;
this.uploadPicture(this.cameraAvatar, path).then(
downloadUrl => {
//after promisse resolved I have the download URL.
this.profileForm.controls['avatarUrl'].setValue(downloadUrl);
// so I can update the user profile
this.profilerProvider.updateProfile(this.profile.id, this.profileForm.value).then(
() => {
toast.present().then(() => {
loader.dismiss();
this.navCtrl.pop();
});
},
error => {
console.error(error);
}
);
},
error => {
console.error(error);
}
);
}
}
uploadPicture(imageData: string, path: string): Promise<string> {
const fileRef = this.afStorage.ref(path);
// create a promisse that returns the downloadUrl from a uploaded picture
// Its necessary to be a promisse, because we need to wait finish upload to get the downloadUrl before update user profile
return new Promise((resolve, reject) => {
if (!imageData) {
// if userdata is empty return the current picture URL
fileRef.getDownloadURL().subscribe(downloadUrl => {
return resolve(downloadUrl);
});
} else {
// uploading a new image
const task = this.afStorage.ref(path).putString(imageData, 'data_url');
// get notified when the download URL is available
task
.snapshotChanges()
.pipe(
finalize(() => {
fileRef.getDownloadURL().subscribe(downloadUrl => {
return resolve(downloadUrl);
}),
err => {
return reject(err);
};
})
)
.subscribe(),
err => {
return reject(err);
};
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment