Access the value of the observable in TypeScript code

I am currently working with Angularfire2 for handling image uploads and downloads. Unfortunately, I have encountered an issue after the removal of 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();
    // receive notification once download URL is available
    task.snapshotChanges().pipe(
        finalize(() => this.downloadURL = fileRef.getDownloadURL() )
     )
    .subscribe()
  }
}

Although I am able to access the downloadURL in the HTML page, I am unsure of how to access it within the function itself.

Answer №1

To retrieve the URL string, you must subscribe to the this.downloadURL Observable. The "async" pipe in HTML functions in a similar way by subscribing and updating the value upon emission.

It's crucial to ensure that this.downloadRef is not null. Therefore, in your code sample, it should be placed within the finalize function.

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

However, there might be better alternatives than using the finalize function. This implementation will only work if the snapshotChanges Observable finishes or encounters an error after the first output. To provide a more comprehensive response, additional context about the situation would be beneficial.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to associate a generic TypeScript type with another type by utilizing its generic parameters?

I am faced with a situation where I have a family of APIs consisting of various related generic types (along with associated constraints). To illustrate this, I have crafted an example using familiar types as placeholders for better understanding. As I wo ...

How can I set an array as a property of an object using the Angular Subscribe method?

I'm attempting to retrieve array values from the en.json translation file in Angular and then bind them to an object property using the code snippet below. Here is the TypeScript code: ngOnInit() { this.en = { dayNamesMin: this.translateS ...

Issues with loading Angular 9 application on Internet Explorer 11

Having trouble with my app not loading in IE 11 after adding ngx-treeview. Encountering the error (SCRIPT1002: Syntax error), Script Error Error point in vendor.js Unsure how to resolve this issue. Works fine in chrome and firefox, but in IE11 all I se ...

Bring in personalized tag to TypeScript

I am working on a TypeScript file to generate an HTML page. Within this code, I want to import the module "model-viewer" and incorporate it into my project. import * as fs from "fs"; import prettier from "prettier"; import React from "react"; import ReactD ...

Retrieve data from REST call to populate Material dropdown menu

I am looking to dynamically populate a dropdown menu with data retrieved from a Rest API. I attempted the following code: <Select id="country-helper"> {array.map((element) => ( <MenuItem value={element.code}>{element.country}& ...

The 'items' property cannot be linked to 'virtual-scroller' as it is not a recognized attribute

I'm currently facing an issue with integrating virtual scroll into my Ionic 4 + Angular project. Previously, I relied on Ionic's implementation of virtual scroll (ion-virtual-scroll) which worked well initially. However, I encountered a major dr ...

Passing a callback to a third-party library resulted in an unexpected error

My React+TypeScript code utilizes a component from a third-party library. <ThirdPartyComponent onSelect={(value: any) => {...}} /> The eslint-typescript tool is flagging this as an error: Unexpected any. Specify a different type. eslint(@type ...

Angular 9 Material table row expansion feature does not automatically hide

I attempted to experiment with my first Angular application using this example as a beginner and encountered partial success: the expandable row initially appears empty before clicking on it, after which it displays as expected. I am unsure why direct expa ...

Should I utilize peerDependencies or dependencies for Angular 2 dependencies when developing an npm package for an Angular 2 library?

When creating an npm package for Angular 2, specifically as Angular 2 services, I typically utilize peerDependencies in the following manner: "peerDependencies": { "@angular/core": "^2.0.0", "rxjs": "5.0.0-beta.12", "zone.js": "^0.6.6" } ...

Error encountered during Typescript compilation: The attribute 'raw' is not found within the context of the entity 'e' in express

In many instances, I have noticed that people use express.raw() or express.raw({type: 'application/json'}) as middleware in their requests... but is .raw() a legitimate method in Express? I am currently working with TypeScript and using Express ...

When utilizing Immer with an Image, an error occurs stating: "Type 'Element' is not compatible with type 'WritableDraft<Element>'."

My goal is to store and retrieve cached images for future rendering on canvas using the drawImage method. To achieve this, I have created a type definition for the cache: type Cache = { image: Record<string, HTMLImageElement>, }; const initialCac ...

Creating a function that takes a second parameter inferred from a mapped type, depending on the first parameter given

Here is a snippet of code similar to the example provided: export enum Group { FOO = 'foo', BAR = 'bar', BIZ = 'biz' } interface Mapping extends Record<Group, any> { [Group.FOO]: {fooString: string; fooN ...

Electron window widens but does not shrink in size

Currently, I am utilizing electron to create an application where I am using ipc messages to expand and retract the width of the app. The frontend is able to trigger these ipc messages successfully, but for some reason, it refuses to go back to a width of ...

The switchMap function in Angular does not trigger the async validator as expected

To ensure that the username entered by the user is unique, I am sending an HTTP request for every input event from the target element. It is important to debounce this operation so that only one HTTP request is made for X consecutive input events within a ...

Incorporate any element into my ngx-bootstrap modal

I am working on creating a dynamic modal popup that can display different components based on the content. Currently, my modal.component.html looks like this: <div class="modal-container"> <div class="modal-backdrop"> </div> <di ...

Mastering Two-Way Binding in Angular 2 with JavaScript Date Objects

I am currently utilizing Angular 2 and have encountered the following code: Within the JS file, this code initializes the employee-variable for the template: handleEmployee(employee : Employee){ this.employee = employee; this.employee.sta ...

What is the best way to find a partial string match within an array of objects when using Jest?

I am currently utilizing the following versions: Node.js: 9.8.0 Jest: 22.4.2 A function called myFunction is returning an array structured like this: [ ... { id: 00000000, path: "www.someUrl.com/some/path/to" } ... ] I ...

Transforming Uint8Array into BigInt using Javascript

I've come across 3 different ways to convert a Uint8Array to BigInt, but each method seems to produce varying results. Can someone clarify which approach is correct and recommended? Utilizing the bigint-conversion library. The function bigintConversi ...

There was an issue with the code: ERROR TypeError: Can't access the length of an undefined property in Angular 4

Encountering this particular issue: LeaderBoardComponent.html:27 ERROR TypeError: Cannot read property 'length' of undefined The error seems to be originating from the following HTML: <div *ngIf="leaderBoardTableData.length > 0"> With ...

The Firebase cloud function has completed execution with a status code of 304

I'm struggling to understand why my function is returning a status code of 304 instead of the expected 200 response. Even though the documents update correctly, I still want to ensure the correct status code is sent back. const firestoreInstance = ad ...