2017-07-29 62 views
1

我试图将所有用户的个人资料照片存储在实时数据库中,但我遇到了问题。Firebase:User.photoUrl to String

当试图用此代码上传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),它显示为 '未定义'。

我认为的第一件事是它不能保存在数据库中,因为它不是一个字符串,所以我尝试从它调用toString(),但我不能。

的toString()错误:

Uncaught TypeError: Cannot read property 'toString' of undefined 

所以,我怎么可以保存photoUrl从火力地堡数据库中的用户(如字符串)?

在此先感谢。

回答

0

对于大多数我试着不要做这种类型的解决方法,最终上传照片到火力地堡寄存,然后设置User.photoURL“photoUri” DB场上传的图片的网址:

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. 
      }); 
     }); 
    }); 
}); 
0

photoUrl是一个可为空字符串,您可以在文档中看到。

因此,您必须在使用之前测试该值是否已设置。

例如:

if (typeof user.photoUrl != 'undefined') { 
    // Use user.photoUrl 
} 
+0

是的,它肯定会阻止任何错误,但_photoUrl_总是“未定义”。我需要把它放在数据库上。我正在寻找一种方法来做到这一点。谢谢你的时间。 – thecalin

+0

默认情况下,您需要使用社交供应商(如Facebook,twiter或google)对用户进行身份验证。否则你需要自己设置它。 – Pipiks

+0

是的,我想_imgUrl_是User.photoURL的问题。无论如何,我使用FirebaseStorage来获取图像的“安全”URL。感谢您的回应! – thecalin