在 .ts 代码中获取 Observable 值

Get Observable value inside .ts code

我正在使用 Angularfire2 上传和下载图像。但是在 getDownloadURL() 被删除后,我被困在这里。

import { finalize } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  template: `
    <input type="file" (change)="uploadFile($event)" />
    <div>{{ uploadPercent | async }}</div>
    <a [href]="downloadURL | async">{{ downloadURL | async }}</a>
 `
})
export class AppComponent {
  uploadPercent: Observable<number>;
  downloadURL: Observable<string>;
  constructor(private storage: AngularFireStorage) {}
  uploadFile(event) {
    const file = event.target.files[0];
    const filePath = 'name-your-file-path-here';
    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() )
     )
    .subscribe()
  }
}

我在 HTML 页面中获取了 downloadURL,但如何进入函数内部?

您必须订阅 this.downloadURL Observable 才能获得 url 字符串。 HTML 中的 "async" 管道基本上做同样的事情。发出值后立即订阅和更新值。

但是你必须确保 this.downloadRef 不为空。所以在你的代码示例中,它必须进入 finalize 函数。

 task.snapshotChanges().pipe(
    finalize(() => {
       this.downloadURL = fileRef.getDownloadURL();
       this.downloadURL.subscribe(url => console.log(url) );
    })
 )

但我不确定 finalize 是否是正确的函数。此代码仅在 snapshotChanges Observable 完成或在第一次发射后出错时才有效。但我需要更多关于背景的信息才能得到更详细的答案。