Reputation: 13
i'm wanting to use the "url" (of the getDownloadURL) out of her, likely, in a variable like this.url. But everything this.url returns is a undefined result. (I've already made all connections to firebase and import's, etc) Anyone knows if exist an way to make that? Thanks in advance.
example image of the app running
var storage = firebase.storage();
var storageRef = storage.ref();
const spaceRef = storageRef.child(`Profis/${this.EMAIL}.png`);
spaceRef.getDownloadURL().then(function(url){this.url = url})
console.log("teste: " + this.url);
Upvotes: 1
Views: 878
Reputation: 599956
The download URL is loaded from the Firebase servers asynchronously when you call getDownloadURL
. Since this may take some time, the code after that call immediately continues. Then when the download URL comes back from the server, Firebase calls the code that you specify in the then
callback.
It's easiest to see this by placing a few log statements in the code:
var storage = firebase.storage();
var storageRef = storage.ref();
const spaceRef = storageRef.child(`Profis/${this.EMAIL}.png`);
console.log("Before calling getDownloadURL()");
spaceRef.getDownloadURL().then(function(url){
console.log("Got download URL");
});
console.log("After calling getDownloadURL()");
When you run this code, the output is:
Before calling getDownloadURL()
After calling getDownloadURL()
Got download URL
This is probably not what you expected. But it does explain why testUrl
is undefined when you print it: the value didn't come back from the server yet.
For this reason, all code that requires the download URL needs to be inside then then()
callback (or called from inside it). So:
var storage = firebase.storage();
var storageRef = storage.ref();
const spaceRef = storageRef.child(`Profis/${this.EMAIL}.png`);
spaceRef.getDownloadURL().then(function(url){
this.url = url
console.log("teste: " + this.url);
});
This is by the way an extremely common source of confusion for developers new to calling asynchronous Web APIs. Since so many APIs function this way though, I recommend spending some time studying it now, so that you are confused about it less frequently going forward. Some sources:
Upvotes: 1