Angular: extracting value from forkJoin nested within another observable's pipe

Here is the scenario that needs to be implemented:

  1. An API call is made which returns a response containing an array of objects.
  2. The objects are then mapped to another array of objects.
  3. For each item in this new array, another API call needs to be made.
  4. The response from the second call should update a value in each object created in step 2.
  5. An observable containing the array of updated objects from step 4 should be returned.

Progress so far includes the following code:

public getWishlist(receiver: Person): Observable<Wish[]> {
    return this.http$.get<IWishlistResponse[]>(environment.apiUrl + 'wishlist/' + receiver.id).pipe(
      map((response) => {
        let wishes: Wish[] = [];
        response[0].wishes.forEach((wish) => {
          wishes.push(new Wish(
            wish._id,
            wish.title,
            wish.price,
            null,
            wish.url
          ));
        });
        return wishes;
      }),
      ????
    );
}

The 'wishes' logged in console.log within the subscribe function of forkJoin are the desired values to be returned in the observable. However, they are not being captured by the observable. What operator should be used instead of 'tap' in order to include the results of the forkJoin pipe in the returned observable?

Answer №1

Consider replacing the tap with a switchMap that transitions to a new observable.

import { switchMap } from 'rxjs/operators';
...
public getWishlist ( receiver : Person) : Observable<Wish[]>{
    return this.http$.get<IWishlistResponse[]>(environment.apiUrl + 'wishlist/' + receiver.id).pipe(
      map( (response) => {
        let wishes: Wish[] = [];
        response[0].wishes.forEach((wish) => {
          wishes.push(new Wish(
            wish._id,
            wish.title,
            wish.price,
            null,
            wish.url
          ));
        });
        return wishes;
      }),
      switchMap( (wishes) => { // update to switchMap for transitioning to new observable
        let wishStateObservables = wishes.map(wish => this.http$.get<wishStatus>(environment.apiUrl + 'wish/' + wish.id + '/state').pipe(catchError(() => of(null))));
        return forkJoin(wishStateObservables); // include return statement here for switchMap
      }),
      map(states => { // remove inner pipe from forkJoin and move it to outer pipe
              states.forEach((state, index) => {
                wishes[index].status = state;
              });
              return wishes;
      }),
    );

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 focus of the input is lost when the value is being edited, specifically in the case where ngFor and ng

I'm facing an issue with a simple list that binds two-way to a parameter hero in my hero.component.ts. Whenever I begin typing in the input field, it seems to lose focus and I have to click on it again. How can I ensure that users are able to edit th ...

I couldn't identify the Material import within the child modules of Angular 2

I am facing an issue with importing custom material.ts modules in my app.module.ts file. I am unable to use Material in components declared at the module root level. However, when I create a child module (ClientModule) and declare a component there, Materi ...

Encountering a type-safety problem while attempting to add data to a table with Drizzle

My database schema is structured like so: export const Organization = pgTable( "Organization", { id: text("id").primaryKey().notNull(), name: text("name").notNull(), createdAt: timestamp("c ...

What steps should I take to address the numerous errors I am encountering in Atom using the Atom linter tool?

My Atom interface is showing the following errors: {Error running gjslint}(x4) {Error running selective}(x4) Upon checking the errors section, I found the following details: [Linter] Error running selective Error: ENOENT: no such file or directory, open ...

What steps should be taken to identify a new path following a call to router.navigate?

Trying to interrupt a route change using a router guard. When I use: this.router.navigate([“myApp/userProfiles”]); After calling this, it passes through the CanDeactivate interface of the guard. The guard then needs to determine the actual destinatio ...

Error encountered: UI-Router state's 'includes' property is not recognized as a valid property in the StateDeclaration type

Prior to initiating the state transition, it is necessary to validate whether the target state falls under a parent state. The MatchCriteria is as follows: this.transition.onStart({ to: function(state) { return state.includes.parentstate; } },() = ...

Angular routing system using hash symbol to navigate to different routes without considering the

As I work on developing an extension, I encountered a challenge when trying to open the popup to a specific route. Despite providing the URL moz-extension://adf...as/dist/extension/index.html#/home/otherpage The popup seems to ignore the #/home/otherpage ...

Exploring RouteReuseStrategy in Angular 2

I followed the RouteReuseStrategy advice provided here, but had to make some adjustments. Specifically, I had to modify the handling of routeConfig.path in the shouldAttach method as it was empty and causing issues with caching. My Angular router version i ...

Tips for Managing Disconnection Issues in Angular 7

My goal is to display the ConnectionLost Component if the network is unavailable and the user attempts to navigate to the next page. However, if there is no network and the user does not take any action (doesn't navigate to the next page), then the c ...

Navigate to a blank page using Angular once the button has been clicked

Having a simple home page with just one button, I wanted the user to be redirected to another page upon clicking the button. However, my attempts to achieve this have not been successful. Here's the code snippet from my app.component.ts file: app.com ...

Encountering Typescript issues following the transition from npm to pnpm

Currently, I am facing a challenge in migrating an outdated Angular JS project from npm to pnpm. The main issue I am encountering is related to typescript errors, particularly the error message that states: error TS2339: Property 'mock' does not ...

Struggling with testing the checkbox when it changes inside the CardHeader Avatar={} component

I've recently implemented a feature similar to the example showcased on MaterialUI's TransferList. However, I'm encountering difficulties accessing a checkbox within the avatar={}. The project utilizes Jest and Enzyme for testing purposes. T ...

Step-by-step guide on setting fa fa-check as the background image for the selected field in Angular 4 with ng-select

I am implementing an ng-select field and would like to display a check mark for the selected option in the dropdown list using fontawesome check. However, I am unsure of how to achieve this. Can anyone provide guidance? HTML: <ng-select class="box" p ...

TypeScript's function types

Regarding my previous inquiry: Transforming PropTypes compatibility into TypeScript If I have this specific function to pass: const displayIcon = () => <span class='material-icons'>account_circle</span> And, the displayIcon func ...

I am looking to personalize a Material UI button within a class component using TypeScript in Material UI v4. Can you provide guidance on how to achieve this customization?

const styling = { base: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', border: 0, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', height: 48, ...

The error message is indicating that the property `match` is being attempted on an undefined object. This issue is puzzling as it does not reference any specific files or

I encountered an issue while working on my project: I kept receiving the error message "Cannot read property match of undefined." Cannot read property 'match' of undefined The error points to a specific line in polyfills.js: process.version.ma ...

Improve your code quality with TypeScript's type checking capabilities

I am currently utilizing TypeScript version 1.4.1 and I have a need to import an external module (specifically "chai") while ensuring type checking compatibility. Yet, I seem to be facing a naming conflict issue with the following code snippet: /// <r ...

Trouble navigating through an index of elastic data? Learn how to smoothly scroll with Typescript in conjunction with

I'm currently using the JavaScript client for Elasticsearch to index and search my data, but I've encountered an issue with using the scroll method. Although I can't seem to set the correct index, I am confident in my technique because I am ...

Getting the data from the final day of every month in a Typescript time-series object array

I am dealing with timeseries data retrieved from an API that consists of random dates like the following: [ { "id": 1, "score": 23, "date": "2023-08-30" }, { "id": 2, "score&qu ...

Supporting Windows desktop within Cordova technology

I am currently seeking the best solution for my upcoming development project. Here are my requirements: - Supported platforms: Android, iOS, Windows Mobile, Windows desktop. - Looking for a unified code base if possible. In the past, I have experience w ...