Isurendrasingh
Isurendrasingh

Reputation: 432

Get Observable value inside .ts code

I'm using Angularfire2 for uploading & downloading images. But after the getDownloadURL() is removed i'm stucked here.

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()
  }
}

I'm getting the downloadURL in the HTML page, but how to get inside the function?

Upvotes: 2

Views: 945

Answers (1)

besserwisser
besserwisser

Reputation: 2710

You have to subscribe to the this.downloadURL Observable to get the url string. The "async" pipe in HTML is basically doing the same thing. Subscribing und updating the value as soon as a value is emitted.

But you have to make sure that this.downloadRef is not not null. So in your code example, it must go into the finalize function.

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

But I am not sure, if finalize is the right function anyway. This code only works, if the snapshotChanges Observable completes or errors after the first emission. But I need more information about the background for a more detailed answer.

Upvotes: 1

Related Questions