从离子3

时间:2018-05-04 22:34:15

标签: javascript node.js angular firebase ionic3

我正在开发离子3手机壁纸应用程序,我正在使用firebase数据库上传照片现在我想在应用程序中显示这些照片

就像我上传3张照片(1.jpg,2.jpg,3.jpg)我写这段代码从数据库中获取它们

 imageSource;
 photo;
 
 
 
 constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.imageSource = (1);
    this.getPhotoURL();
  }

  getPhotoURL() {
    firebase.storage().ref().child('/' + this.imageSource + '.jpg').getDownloadURL().then((url) => {
      this.photo = url;
    })
  }

在html中我写这个

<ion-col>
     <img src="{{photo}}">
</ion-col>

但只能获得我写的照片名称。|| this.imageSource =(1);“||。 每次我想要一张新照片我都要做一个新功能

所以如何为我上传的任何照片自动更新 或者我需要一个更好的代码,可以通过简单的方式为我提供3张照片

1 个答案:

答案 0 :(得分:0)

当你上传文件时,你必须使用uploadTask.snapshot.downloadedURL获取downloadURL并保存它,就像这样

public downloadedUrls: [];

var uploadTask = storageRef.child('images/rivers.jpg').put(file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){

  // Observe state change events such as progress, pause, and resume
  // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
  var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
  console.log('Upload is ' + progress + '% done');
  switch (snapshot.state) {
    case firebase.storage.TaskState.PAUSED: // or 'paused'
      console.log('Upload is paused');
      break;
    case firebase.storage.TaskState.RUNNING: // or 'running'
      console.log('Upload is running');
      break;
  }
}, function(error) {
  // Handle unsuccessful uploads
}, function() {
  // Handle successful uploads on complete
  // For instance, get the download URL: https://firebasestorage.googleapis.com/...
  this.downloadedUrls.push(uploadTask.snapshot.downloadURL);
});

使用downloadedUR,您可以保存在一个数组中,然后,您可以使用保存的图像中的所有网址在html中循环此数组,如下所示:

<ion-col *ngFor="let photo of downloadedUrls">
   <img src="{{ photo }}">
</ion-col>
例如,

其中downloadedUrls可以是字符串数组。我让自己明白了吗?

希望它有所帮助。

Ps:我从Firebase Storage Docs获取的上传方法,您可以查看

https://firebase.google.com/docs/storage/web/upload-files?hl=pt-br