Hold off until the observable has finished

map((tasks): any => {
  return tasks.map(task => ({
      ...task,
      status: this.getStatus(task.owner, task.delegationState, task.assignee, task.id),
  }));
});

I utilize the getStatus method within the map() operator from rxjs.

getStatus(
  owner: string | null, 
  delegationState: string | null, 
  assignee: string | null, 
  id: string): string {

  if (assignee) {
      if (!owner) {
          if (!delegationState) {
              this.caseService.getUserOperationHistory({
                  taskId: id,
                  entityType: 'T',
                  operationType: 'Claim',
              }).subscribe((res) => {
                  return 'Claimed';
              });
          } else {
              return 'Assigned';
          }
      }

      if (delegationState === 'PENDING') {
          return 'Delegated';
      }
      if (delegationState === 'RESOLVED') {
          return 'Assigned';
      }
  }

  return 'Unassigned';
}

While executing the asynchronous code in getUserOperationHistory(), it runs synchronously causing a premature result of 'Unassigned' instead of 'Claimed'. How can I ensure that the async code completes before returning a value?

Answer №1

When dealing with nested calls, it's best to utilize forkJoin to ensure that the values are correctly returned. Attempting to return values from outside of subscribe may lead to unexpected results. Here is a suggested approach:

switchMap((tasks: any) => forkJoin(tasks.map(task => 
    this.getStatus(...).pipe(
      map(data => ({...task, status: data}))
    )
  )
);

In the case that getStatus only returns a string, you can use of('stringHere') to wrap it in an observable.

It's also advisable to avoid using any and instead type your data for better clarity and consistency.

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

The TypeScript extension of a type from an npm package is malfunctioning

I am utilizing the ws package to handle WebSockets in my Node.js project. I aim to include a unique isHealthy attribute to the WebSocket class. The approach I have taken is as follows: // globals.d.ts import "ws" declare module "ws" { ...

Saving the contents of a JSON query field to a file using Angular

Currently, I am working on an Angular application that interacts with a JSON API to extract specific fields from the data and save them to a file. For instance, if the API query yields: [{"id":1,"name":"Banana"},{"id" ...

The setInterval function is active in various components within Angular 6

Recently, I started using Angular(6) and incorporated the setInterval function within a component. It's functioning properly; however, even after navigating to another route, the setInterval continues to run. Can someone help me determine why this is ...

The use of the .reset() function in typescript to clear form data may lead to unexpected

I've been trying to use document.getelementbyID().reset(); to reset form values, but I keep running into an error in TypeScript. Property 'reset' does not exist on type 'HTMLElement'. Here's how I implemented it: const resetB ...

What is the quickest method for setting up types for node packages?

Whenever I need to use typed packages in my Node.js projects, there are two steps I have to take: Firstly, install the original package. For example: npm install express -S Secondly, install its type definition package. npm install @types/express -D I f ...

`Why isn't GetServerSideProps being triggered for a nested page in Next.js when using Typescript?

I have been working on a page located at /article/[id] where I am trying to fetch an article based on the id using getServerSideProps. However, it seems that getServerSideProps is not being called at all as none of my console logs are appearing. Upon navi ...

An issue detected in the index.esm.js file located in the firebase/firestore module within the node

I've encountered an issue while starting my angular project using the npm-start command. Here is the error I came across: ERROR in ./node_modules/firebase/firestore/dist/index.esm.js Module not found: Error: Can't resolve '@firebase/firest ...

Duplicate items within an array were found when receiving Node.js response data in Angular

I'm facing an issue where duplicate elements are being displayed in an Angular table when receiving data from Node.js. The array sent by Node.js contains 2 elements, but somehow it appears as 4 elements in the Angular table. This discrepancy is puzzli ...

Guide on updating a property key in Firebase real-time database with Angular 7

Is it possible to modify the key of a property in my firebase database that I have been struggling with? ...

Issue encountered with TypeORM and MySQL: Unable to delete or update a parent row due to a foreign key constraint failure

I have established an entity relationship between comments and posts with a _many-to-one_ connection. The technologies I am utilizing are typeorm and typegraphql Below is my post entity: @ObjectType() @Entity() export class Post extends BaseEntity { con ...

Issue TS7053 occurs when trying to access any index of the target of a React.FormEvent<HTMLFormElement>

I've been working on adapting this tutorial to React and TypeScript. Here is the code snippet I have implemented for handling the onSubmit event: const handleSignUp = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); ...

Enhance your TypeScript arrays using custom object equality functions

I am looking to utilize array functions such as contains and unique, but I want them to compare equality using my custom equals function. For instance: let arr = [{id:1,..//some more},{id:2,..//some more},{id:3,..//some more}] I need the following code ...

Numerous documents for route definitions

Typically, I usually have all my route definitions in a single file, such as app.routing.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@a ...

Collaborating on data through module federation

Currently, I am in the process of developing a Vue.js and TypeScript application using Vite. In addition, I am utilizing the vite-module-federation-plugin for sharing code across different applications. My main inquiry revolves around whether it is possibl ...

Transforming a Bootstrap 4 HTML project into Angular 9

After stumbling upon a beautiful HTML template that caught my eye, I realized it was built using Bootstrap. Luckily, I came across tutorials on how to convert such templates into Angular 6 projects, making the process seem quite straightforward (like this ...

What is the best tool for setting up an ftp connection to a z/OS mainframe and downloading files to the local machine within an angular web application?

My goal is to allow the user of the webapp to enter a specific file located on the server via a text field, and then have that file downloaded to their local machine. There's also an optional feature where the user can input the login credentials for ...

"Encountered a problem with Next JS API while trying to fetch data from the app directory

import { NextResponse } from "next/server"; export async function POST(request: Request) { const data = await request.json(); console.log(data); return NextResponse.json({ foo: "boo" }); } next version = "next": &quo ...

Using Angular 5 with ng2-smart-table to conditionally hide or disable the actions column

I am working with a table generated by ng2-smart-table. The data in the table can be in two states: Draft and Ready. I need to implement a condition where if the data.status = 'Draft', the actions column for CRUD operations is displayed, but if t ...

Issue: Missing provider for t specifically when running in production mode

I've been researching and found that missing modules or services could be the cause of this issue, but I have double-checked and everything seems to be in order. Here is the complete error message: vendor.96643eaf6ee79e7b894d.bundle.js:1 ERROR Error ...

Improving Image Loading Efficiency in Next.js - Enhancing Performance by Preloading Images

Currently, I am working on a project in Next.js that involves a scroll-based image loading component. The method I am using to fetch and load images dynamically based on the scroll position is causing performance problems and leading to a less than ideal u ...