尝试使用变量创建AngularFireStorageReference时出现问题

时间:2018-11-16 02:36:06

标签: angular firebase google-cloud-firestore firebase-storage

使用以下示例代码创建存储引用时,我没有任何问题。但是,当我用this.id替换“ 1234”时,在屏幕截图中出现了以下问题。我该如何解决?我在网上阅读的所有文档都表明该方法可以正常工作。

export class NewListComponent implements OnInit {

uploadPercent: Observable<number>;
downloadURL: Observable<string>;
uploadProgress: Observable<number>;
ref: AngularFireStorageReference;
task: AngularFireUploadTask;
uploadState: Observable<string>;
id:string;
imgObsArray: Observable<string>[] = new Array();

  constructor(private afStorage: AngularFireStorage) {

  }

  ngOnInit() {
  }


uploadFile(event) {

this.id = Math.random().toString(36).substring(2);
this.ref = this.afStorage.ref("1234");
this.task = this.ref.put(event.target.files[0]);
this.uploadState = this.task.snapshotChanges().pipe(map(s => s.state));
this.uploadProgress = this.task.percentageChanges();

  this.ref.getDownloadURL()
  .subscribe(avatarUrl => {
      this.downloadURL = avatarUrl
      this.imgObsArray.push(this.downloadURL)
     console.log(avatarUrl + " This is the avatarUrl " + this.downloadURL + " This is the downloadURL ");
  }, (error) => {
     console.error(error);
  });

}

}

错误

enter image description here

基于反馈的更新代码

uploadFile(event) {
const id = Math.random().toString(36).substring(2);

console.log(id + " THIS IS THE RANDOM ID")

this.ref = this.afStorage.ref(id);

this.task = this.ref.put(event.target.files[0]);

this.uploadState = this.task.snapshotChanges().pipe(map(s => s.state));

this.uploadProgress = this.task.percentageChanges(); 

this.task.snapshotChanges().pipe( 
    finalize(() => this.downloadURL = this.ref.getDownloadURL())).subscribe(); 

this.downloadURL.pipe(
    filter( url => url !== undefined),
    tap(avatarUrl => { this.imgObsArray.push(avatarUrl),
    console.log(avatarUrl + " This is the avatarUrl " + avatarUrl + " This is the downloadURL "); }),
    catchError( error => { 
    console.error(error); 
    return Observable.throw(error);}
)).subscribe();

}

enter image description here

1 个答案:

答案 0 :(得分:0)

添加为一个答案,您应该在完成快照更改后检索downloadUrl,如存储文档中所述。要解决管道错误,最好将this.downloadUrl订阅移动到ngOnInit。

PS:经过进一步讨论,看来ref.getDownloadUrl最初可以返回null。