Я пытаюсь сохранить все фотографии профиля пользователя в базе данных реального времени, но у меня возникла проблема.
При попытке загрузить PhotoUrl с помощью этого кода появляется эта ошибка.
Код:
var user = firebase.auth().currentUser;
user.updateProfile({
// Here, "name" and "imgUrl" are parameters of parent function.
// I don't think this is the reason, but if it helps,
// "imgUrl" always come from a <img> src.
displayName: name,
photoUrl: imgUrl
}).then(function(){
// Here is where I try to upload all to the database
firebase.database().ref("/Usuarios/" + user.uid).set({
"email": email,
"name": name,
"photoUri": user.photoUrl, // This is where I think the problem originates.
"uid": user.uid // This calls user again, and it works perfectly.
});
});
Ошибка:
Uncaught Error: Firebase.set failed: First argument contains undefined in property 'Usuarios.kD1tD1NAmsaGiW0zj6lFz9GDWro1.photoUri'.
Когда я предупреждаю (user.photoUrl), он отображается как "undefined".
Первое, что я подумал, это то, что он не может быть сохранен в базе данных, потому что это не String, поэтому я попытался вызвать toString() из него, но я не могу.
Ошибка toString():
Uncaught TypeError: Cannot read property 'toString' of undefined
Итак, как я могу сохранить photoUrl от пользователя (как String) в базе данных Firebase?
Заранее спасибо.
В большинстве случаев я старался не делать этого типа обходных решений, закончил загрузку фотографии в хранилище Firebase, а затем установил User.photoURL и поле "photoUri" DB в URL-адрес загруженного изображения:
user = firebase.auth().currentUser;
avatarStgRef = firebase.storage().ref("Usuarios/" + user.uid + "/avatar.jpg");
// imgFile the Photo File.
avatarStgRef.put(imgFile).then(function(snapshot){
snapshot.ref.getDownloadURL().then(function(url){ // Now I can use url
user.updateProfile({
photoURL: url // <- URL from uploaded photo.
}).then(function(){
firebase.database().ref("Usuarios/" + user.uid).set({
"photoUri": url // <- URL from uploaded photo.
});
});
});
});
PhotoUrl - это нулевая строка, как вы можете видеть в документации.
Поэтому вам нужно проверить, установлено ли значение перед его использованием.
Например:
if (typeof user.photoUrl != 'undefined') {
// Use user.photoUrl
}