上传图片参考网址保存在Firestore中

时间:2018-08-03 03:20:00

标签: angular firebase google-cloud-firestore angularfire2

我的堆叠闪电战:https://stackblitz.com/edit/upload-image-ref-firestore?embed=1&file=src/app/app.component.html

我正在使用AngularFire2上传图像,我想知道如何将Firebase Storage图像的引用保存在Firestore文档中。

enter image description here

我正在尝试,但我得到的只是一个空字段:

enter image description here

有什么主意吗?

component.ts

Meal

html

import { Component, OnInit, ViewChild  } from '@angular/core';
import { finalize } from 'rxjs/operators';
import { AngularFireStorage } from 'angularfire2/storage';
import { Observable } from 'rxjs';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { FirebaseService } from './services/firebase.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {

  tests: Observable<any[]>;
 
  uploadPercent: Observable<number>;
  downloadURL: Observable<string>;

  forma: FormGroup;
  @ViewChild('f') form;

  constructor(fb: FormBuilder, private fs: FirebaseService, private storage: AngularFireStorage ) { 
    this.forma = fb.group ({
      imagenDestacada: [ '', Validators.required],

    })
  }

  ngOnInit() {
    this.tests = this.fs.getTests();
  }

  uploadFile(event) {
    const file = event.target.files[0];
    const filePath = `proyectos4/name1`;
    const fileRef = this.storage.ref(filePath);
    const task = this.storage.upload(filePath, file);

    // observe percentage changes
    this.uploadPercent = task.percentageChanges();
    // get notified when the download URL is available
    task.snapshotChanges().pipe(
        finalize(() => {
        this.downloadURL = fileRef.getDownloadURL()
        this.fs.addTest(this.forma.value)
        console.log( this.downloadURL ) 
      })    
    )
    .subscribe()

  }


}

1 个答案:

答案 0 :(得分:1)

调用fileRef.getDownloadURL()不会直接返回下载URL。相反,它返回一个承诺,该承诺将在下载URL可用时进行解析。这意味着您需要等待承诺解决,然后才能记录下载URL或将其写入数据库:

task.snapshotChanges().pipe(
  finalize(() => {
    fileRef.getDownloadURL().then((url) => {
      this.downloadURL = url;
      this.fs.addTest(this.forma.value)
      console.log( this.downloadURL ) 
    });
  })    
)