Angular has got us covered with its latest feature - combining Async Await with an EventListener

I have been facing this issue for the past day and need help creating a specific scenario:

<img [src]="userdp | async" />

In my component.ts file, I want to include only this line:

this.userdp = this._userService.getUserDp();

Here is the code within the getUserDp() method:

async getUserDp() {
    return await
    this._http.get(APIvars.APIdomain+'/'+APIvars.GET_USER_DP,  { responseType: 'blob' }).toPromise().then( image => {
        if(image['type'] === 'application/json') {
          return null;
        }
        const reader = new FileReader();
        reader.addEventListener('load', () => {
           **return this._dom.bypassSecurityTrustResourceUrl(reader.result.toString());**
        });
        }, false);
        if (image) {
          reader.readAsDataURL(image);
        }
    });
  }

The promise does not wait for the reader to load in the EventListener, any immediate return statement produces the desired result. The bolded line contains the main data to be returned.

Thank you

Answer №1

If you want to simplify your life and make it easier for future code readers, consider creating a promise-based FileReader method to eliminate callbacks in one place.

// Create a promise that resolves when the FileReader 'load' event is triggered
async function readAsDataURL(image) {
  const reader = new FileReader();
  return new Promise((resolve, reject) => {
    reader.addEventListener('load', () => {
      resolve(reader.result.toString());
    });
    // Add an error handler if needed
    reader.readAsDataURL(image);
  });
}

With the file handling code transformed into promises, using it becomes much more straightforward...

async getUserDp() {
  // Set temporary variables for readability
  const url = APIvars.APIdomain+'/'+APIvars.GET_USER_DP;
  const options = { responseType: 'blob' };
  
  // Use async/await instead of .then()
  const image = await this._http.get(url,  options).toPromise();
  
  // Check if the image is valid before proceeding
  if (!image || image['type'] === 'application/json') return null;
  
  // Read the file asynchronously using the created method
  const readerResult = await readAsDataURL(image);
  return this._dom.bypassSecurityTrustResourceUrl(readerResult);
}  

Answer №2

Commit to your vow

    writer.onload = function (e) {
       
    }; 

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

Show a reset button in an Angular 2 reactive form only when the form has unsaved changes

I am working with a reactive form and need to add a reset button that will return the form values to their initial state. The reset button should only be visible if the form is dirty. Here is the form definition: this.form = new FormGroup({ firstName: ...

Encountering a problem when attempting to add ngrx to an Angular project

I'm currently in the process of setting up ngrx in my Angular application. After running the command ng add @ngrx/store@latest An error occurred with the following details: npm resolution error report 2022-07-07T20:36:16.089Z While resolving: [em ...

Learn how to retrieve the return data from two combined objects using Angular's TypeScript syntax

I've encountered an issue with TypeScript syntax, specifically when a WebAPI returns a DTO containing two objects. The object being returned looks like this: { "userList": [{ "id": 1, "firstNm": "John", "lastNm": "Doe" }, ...

Empty initial value for first item in array using React hooks

My goal is to store an array that I retrieve from an API in a useState hook, but the first entry in my array always ends up empty. The initial array looks like this: (3) ["", "5ea5d29230778c1cd47e02dd", "5ea5d2f430778c1cd47e02de"] The actual data I recei ...

Creating OL maps with subpar quality using the Ionic framework

I'm currently facing an issue while trying to load the OL map with Ionic. When I use 'ionic serve' to load it, the map displays perfectly in the browser. However, when I try to load the map on a mobile device, the quality drastically decreas ...

Angular HTML is throwing an error related to object arrays

Is there a way to display only specific fields of an array? <div class="form-check" *ngFor="let periodo of filterPeriodos()"> <div>{{periodo.periodos | json}}</div> <input class="form-check-input mr- ...

Using Typescript to create a Checkbox Grid that displays pipe-delimited values and implements a custom validation rule

I am currently working with a checkbox grid that contains pairs of AccountIds (consisting of x number of digits) and file names separated by a pipe delimiter. The file names are structured to always begin with either PRC or FE followed by a varying combin ...

Turning a JSON string into interpolation within an Angular application

I received a JSON response that looks like this: { someText: "Order in {000} 12pm PST for early shipping"; cutofftime : "10000000" } What is the most effective way to replace the '{000}' with the dynamic value stored in &quo ...

The useEffect hook is triggering multiple unnecessary calls

Imagine a tree-like structure that needs to be expanded to display all checked children. Check out this piece of code below: const { data } = useGetData(); // a custom react-query hook fetching data from an endpoint Now, there's a function that fin ...

ASP.NET is being used to host an angular application, but the deployUrl feature is

I have a .NET 6.0 ASP.NET application where I've set up a route /ngxapp to serve my Angular 13 application. The Angular app is stored in the wwwroot/ngxapp folder, as shown below. I've been using this code for years to deliver the Angular app: ...

What is the process for incorporating custom parameters into Angular 5 DataTables?

Currently, I am tackling a project that involves Angular5 and PHP as the backend. However, I have hit a roadblock at this stage of development. Below is the snippet of code causing me trouble: this.dtOptions = { pagingType: 'full_numbers', p ...

Generating a form structure from json containing repeated inputs: Control with path formArray could not be located

Currently, I am in the process of constructing a form using JSON data. My backend is implemented with Spring Boot, which returns the following object to an Angular frontend: { "controls": [ { "name": "genre", ...

There are no HTTP methods being exported in this specific file. Remember to export a named export for each individual HTTP method

Currently, I am working on a React.js/Next.js project that incorporates Google reCAPTCHA. The frontend appears to be functioning properly as I have implemented print statements throughout the code. However, I am encountering an error in the backend display ...

The triggering of routing in Next.js is not established by useEffect

I'm facing an issue with my Next.js dynamic page that uses routing based on steps in the state. The route is supposed to change whenever a step value changes, like from null to "next" or back. However, the useEffect hook doesn't seem to be reacti ...

Include a .done() callback within a customized function

In the small class, I have included these functions: var Ajax = { // Send new entry data to database endNewEntry: function (json) { $.post("/controllers/insertEntry.ajax.php", {"json": json}); }, loadView: function (view, target, extra) { ...

What is the reason behind the inability of the Angular/TypeScript HTTP GET method to accept a JSON object as a parameter

EXAMPLE 1 passJSONObj(){ let name = 'user names', let email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7a2a4b2a5b2bab6bebb97b3b8bab6beb9f9b2afa3">[email protected]</a>&ap ...

Verify if Angular 2 route parameters have a legitimate value

Within an angular2 component, I have the following code: ngOnInit() { this.route.params .switchMap((params: Params) => this.elementsService.getElement(+params['id'])) .subscribe(element => { this.elementToEd ...

Using Typescript for Asynchronous Https Requests

I've been attempting all day to make an https request work. My current code isn't functioning as expected; when I run it, I encounter an "Unhandled error RangeError: Maximum call stack size exceeded at Function.entries" import * as https from &q ...

In Ionic 2, any modifications made to the data model will only be reflected in the user interface after there is

Q) Why does my data seem to magically appear on the UI after interacting with it, even though I have made changes in the backend? For instance, when fetching and updating data bound to a list, such as: this._LocalStorageService.getClients().then( (data ...

Understanding the attribute types in Typescript React

While working on code using Typescript + React, I encountered an error. Whenever I try to set type/value in the attribute of <a> tag, I receive a compile error. <a value='Hello' type='button'>Search</a> This piece o ...