Xiaofan Wu Xiaofan Wu - 4 months ago 43
AngularJS Question

How do I detect if a particular firebase storage path data has changed

firebase database has a function where I can retrieve data again when something changed in the path

firebase.database().ref('users/' + Auth.uid + '/profileImg').on('value', function(snapshot) { //do things when the data changed});


I was wondering if anyone know if firebase storage does the same thing? For example if I upload another profile pic, how can I can retrieve that imageUrl?

I understand I can retrieve it in the way below, but since I want to detect changes in another controller that is not in the same controller as the upload place, this method would not work.

uploadTask.on('state_changed', function (snapshot) {
// Observe state change events such as progress, pause, and resume
// See below for more detail
}, function (error) {
// Handle unsuccessful uploads
}, function () {
$scope.userProfile = uploadTask.snapshot.downloadURL;
});
}, function (error) {
console.error(error);
});


Thank you!!

Answer

Firebase Storage has no built-in capability to proactively alert clients when a file is changed.

This is something you can easily build by combining Firebase Storage with the Firebase Realtime Database. Keep the downloadURL of your file in the database and add a lastModified timestamp:

images
  $imageid
    downloadUrl: "https://downloadUrl"
    lastModified: 123873278327

Whenever you upload/update an image in Firebase Storage, update the downloadUrl/timestamp in the database:

uploadTask.on('state_changed', function (snapshot) {
    // Observe state change events such as progress, pause, and resume
    // See below for more detail
}, function (error) {
    // Handle unsuccessful uploads
}, function () {
    $scope.userProfile = uploadTask.snapshot.downloadURL;
    databaseRef.child('images').child(imageId).set({
        downloadUrl: uploadTask.snapshot.downloadURL,
        lastModified: firebase.database.ServerValue.TIMESTAMP
    })
});

Now you can know when an image has been modified, by listening to the database location for that image:

databaseRef.child('images').child(imageId).on('value', function(snapshot) {
  // take the downloadUrl from the snapshot and update the UI
});