Tips for waiting for an observable loop

When using my application, the process involves uploading a series of images in order to retrieve the file IDs from the system. Once these IDs are obtained, the object can then be uploaded.

async uploadFiles(token: string):Promise<number[]> {
    let ids = Array<number>();
    this.images.forEach((image: ImageData) => {
      this.fileService.uploadFile(image, token).subscribe((result: File) => {
        ids.push(result.data.id);
      })
    });
    return ids;
  }

The main objective of this function is to collect and return all the IDs. However, due to the nature of the fileService subscribe method, it currently only returns an empty array.

Answer №1

The issue at hand is that the fileService.uploadFile.subscribe() function operates asynchronously. This means that the subscription will wait for a result to be returned, but the code execution continues immediately after the subscription line. Therefore, when the return ids are processed right after the subscription, there is no value available yet and nothing is pushed into the ids array, resulting in an empty array being returned.

To address this problem, you can declare ids as a global variable so that data can be pushed into it once the result is ready. Alternatively, you can modify the function to return an Observable and use Subjects to emit values, as demonstrated in the revised code snippet below.

private idsSubject = new Subject<number[]>();

async uploadFiles(token: string): Observable<number[]> {  
    this.images.forEach((image: ImageData) => {
        this.fileService.uploadFile(image, token).subscribe((result: File) => {
            this.idsSubject.next(result.data.id);
        })
    });
    return this.idsSubject.asObservable();
}

To access the ids, subscribe to this function by calling uploadFiles('my string').subscribe((id) => this.ids.push(id)). Give this solution a try and let me know if it resolves the issue.

Answer №2

To successfully upload data, you should make sure to return an Observable and utilize switchMap for calling the second API.

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

Pass a React component as a required prop in Typescript when certain props are necessary

I am currently working on a project where I need to create a custom TreeView component using React and Typescript. My goal is to have the ability to inject a template for each TreeNode in order to render them dynamically. My main challenge right now is fi ...

Tips for resolving conflicts between sequelize and angular within a lerna monorepo using typescript

Managing a monorepo with Lerna can be quite challenging, especially when working with both Node.js and Angular in the same project. In my setup, Angular is using "typescript": "~3.5.3". For Node.js to work seamlessly with Sequelize, I have the following ...

I'm curious about the equivalent of "ng serve" for nodejs. Do other languages have similar tools available?

ng serve has revolutionized my workflow. With a simple save, I can instantly see the changes in my Angular code reflected in the running instance of my project, allowing me to quickly iterate on my work. But why doesn't a similar tool exist for other ...

The save icon is the lone absentee in the material table

There seems to be an issue with the save icon not showing up in the editable table. The icons for outside actions are functioning properly, but the ones for inner actions are not working. Please click on the update action below: https://i.sstatic.net/Pmae ...

Problem with Anular5 - "this" not functioning correctly inside of ready()

I am encountering an issue in graph.component.ts this.cContainer = cytoscape ( { ready: function(e) { this._dataService.setResultData(); } }); However, I am getting the following error message: ERROR TypeError: Cannot read property &ap ...

Using an Object as a parameter in a Typescript function

I am currently working on an Angular component that includes a function. Within this function, I need to pass an Object as a parameter and invoke the function with these parameters. It has been some time since I last worked with Angular, where "any" was ty ...

Troubleshooting issue: Unable to successfully update dynamically loaded routes in real-time

I have been attempting to make changes to routes in a lazy-loaded feature module, but I have not been successful. I have tried various methods, including using router.reset(newRoutes), however, none of them have been effective. (Working with Angular 9) exp ...

Using the async pipe on the MatTable datasource does not result in sorting functionality, but the table contents are updated correctly

I am encountering an issue with my MatTable that is not sorting when one of the headings are clicked, even though the arrow icon appears. The data loads and refreshes correctly when changes are made to the underlying data, but sorting seems to be a challen ...

Function overloading proving to be ineffective in dealing with this issue

Consider the code snippet below: interface ToArraySignature { (nodeList: NodeList): Array<Node> (collection: HTMLCollection): Array<Element> } const toArray: ToArraySignature = <ToArraySignature>(arrayLike: any) => { return []. ...

Issue with Angular Material date picker: Date Parsing UTC causing dates to display as one day earlier

After exploring numerous threads related to this issue and spending several days trying to find a solution, I may have stumbled upon a potential fix. However, the workaround feels too messy for my liking. Similar to other users, I am encountering an issue ...

DomSanitizer in Angular is not able to bind to an Angular component

Trying to dynamically insert HTML content into a DIV has been successful when done statically. The following code is functioning properly: <popover-content #pop1 title="Cool Popover" placement="right" ...

Angular 11 project facing issues with Bootstrap 5 tooltip functionality

Embracing the power of Bootstrap 5.0.2 in an Angular 11 project, I included the following code: index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compa ...

The functionality of Ionic's infinite scroll feature is limited due to its dependence on the window object

The issue at hand is that the scrolling functionality within the div is not connected to the window, resulting in no action when the user scrolls. While infinite scrolling works flawlessly in a scrollable window, I require a specific connection to the scro ...

A Error occurs if ReactQuill is used without defining the document object

Recently, I embarked on a journey with both next.js and ReactQuill. However, upon running yarn build, an unexpected obstacle arose: info Creating an optimized production build - info Compiled successfully - info Linting and checking validity of types - in ...

Error: In Angular 4, there is an issue where trying to access the length property of an undefined property results in a

How to Fix TypeError: Cannot Read Property 'length' of Undefined in Angular 4 This is the code snippet that is causing the error: export class UserComponent implements OnInit{ roles:IUserRole[]; sourseRoles: SelectedItem[]; selectedRole:a ...

Module '.tmp/Rx.min.js' could not be located

My system runs on Ubuntu os version 16.04 with Node v6.6.0 and Npm 3.10.3. I'm currently setting up a project with gulp, but encountering a common issue: Error Message: Cannot find module '.tmp/Rx.min.js' When running the command below to ...

Tips for creating PrimeNG tables with columns that automatically adjust in size

Is there a way to automatically adjust and resize the columns in my PrimeNG table? I'm looking for a method to make this happen. Can you help me achieve this? ...

Utilize Hardhat and NPM to distinguish between unit tests and integration tests efficiently

Struggling with setting up two commands in my package.json for running unit tests and integration tests. I am having trouble defining the location of the testset for each type of testing. Within the scripts section of my package.json, I have created two c ...

Separate HTTP responses into multiple Observables

I need assistance in splitting a HTTP response into different Variables/Observables. The returned data is in JSON format: [ { "status": [ { "id": 1, "value": "active"}, { "id": 2, "value": "inactive"} ] }, { "type": [ ...

The selected value of the PrimeNG p-checkbox cannot be determined using a function when binding to [ngModel]

These are the rows of my custom p-table <tr> <td>{{user.userName}}</td> <td>{{use.userSurname}}</td> <td *ngFor="let group of groups"><p-checkbox [(ngModel)]="showVal ...