Iterate and combine a list of HTTP observables using Typescript

I have a collection of properties that need to be included in a larger mergeMap operation.

this.customFeedsService.postNewSocialMediaFeed(this.newFeed)
            .mergeMap( newFeed => this.customFeedsService.postFeedProperties( newFeed.Id, this.feedProps))
            .mergeMap(newProps => this.customFeedsService.preloadSocialMediaFeed(newProps.FeedId))
            .subscribe(data => console.log(data), err => console.log);

Within my service, I iterate through the properties to generate a single Observable that feeds into the mergeMap process.

public postFeedProperties( feedId: number, props: FeedPropertyApi[] ): Observable<any> {
    let observeGroup = new Observable<any>();
    for(let prop of props){
        prop.FeedId = feedId;
        observeGroup.concat(this.apiService.postData(this.feedPropertyApiUrl, prop, true)
            .map(res => res.json()));
    }

    return observeGroup
    // return this.apiService.postData(this.feedPropertyApiUrl, props[0], true)
    //          .map(res => res.json()).concat(this.apiService.postData(this.feedPropertyApiUrl, props[1],true)
    //          .map(res => res.json())).concat(this.apiService.postData(this.feedPropertyApiUrl, props[2], true)
    //          .map(res => res.json()));
}

While the commented code works perfectly fine, I encounter a

Cannot read property 'subscribe' of undefined
error when running the loop. What could possibly be causing this issue within the loop?

Answer №1

Have you experimented with replacing 'of' with 'as' in your for loop statement?

for(let prop as props) {...}

If the issue persists, can you provide additional details on where the code is encountering errors and whether it occurs during the initial iteration?

Answer №2

Shoutout to Eliseo for providing the solution. This is how I integrated the code into my project.

let groupToObserve: Observable<any>[] = [];
    for(let property of properties){
        property.FeedId = feedIdentifier;
        groupToObserve.push(this.apiService.postData(this.feedPropertyApiUrl, 
        property, true)
            .map(response => response.json()));
    }
return Observable.forkJoin(groupToObserve).map(result => result);

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

Ways to ensure TypeScript shows an error when trying to access an array index

interface ApiResponse{ data: Student[]; } interface Student { name: string; } Imagine a scenario where we receive an API response, and I am confident that it will contain the data field. However, there is a possibility that the data could be an empty ...

shifting the angular directives to alternate the bootstrap class of hyperlinks

I have a collection of hyperlinks displayed on my webpage. <a href="#" class="list-group-item list-group-item-action active" routerLink='/route1' >Explore First Link</a> <a href="#" class="list-group-item list-group-item-action" r ...

What impact do Angular Signals have on RXJS Observables and how does this influence change detection within the framework?

As I transition to Signals in my Angular App, I am encountering challenges in identifying best practices and dealing with unexpected behaviors. Here is a snippet of my code which includes a userService and two Components: export class UserService { priva ...

Issues with hydrating React local storage hook in custom implementation within NextJS

Currently facing an issue while implementing the localstorage hook in NextJS. The error message I am encountering is: Error: Hydration failed because the initial UI does not match what was rendered on the server.. Any suggestions on what might be causing ...

Can we define the input and return types for functions using httpsCallables?

I have implemented a callable function in my app to update user claims. The functions are written in Typescript and I have used an interface to define the required data shape for the function. My objective is to make it easier for any developer on the tea ...

Challenges with exporting dynamically generated divs using jspdf in an Angular 2 project

I have been utilizing the jspdf library to print div elements in my current project. But I recently discovered an issue where dynamic content within a div is not being printed correctly. Specifically, when incorporating simple Angular if statements, jspdf ...

Angular2 - Error: The view has been destroyed and cannot be updated: detectChanges

My application keeps encountering this persistent error: extensions::uncaught_exception_handler:8 Error in event handler for runtime.onMessage: Attempt to use a destroyed view: detectChanges at ViewDestroyedException.BaseException [as constructor] (chrome ...

Built-in Handlebars helper for nested iteration - no results displayed

I'm currently facing an issue with using an iteration helper within another one. Strangely, the inner helper isn't producing any output. Here's a snippet of the handlebars template I'm working with: {{#people}} <h4>{{firstNa ...

Error encountered while running npm build: Typescript issue within plotly.js/index.d.ts

Trying to implement this code snippet: import createPlotlyComponent from 'react-plotly.js/factory'; const Plot = createPlotlyComponent(window.Plotly); https://i.sstatic.net/2rI0a.png in my React project implemented in TypeScript. Encountered a ...

Error Uncovered: Ionic 2 Singleton Service Experiencing Issues

I have developed a User class to be used as a singleton service in multiple components. Could you please review if the Injectable() declaration is correct? import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/ht ...

Issue with Jest mock function failing to trigger axios instance function causing it to return undefined

I initially found a solution on this StackOverflow thread However, I wanted to add my own helper function that generates a fresh Axios instance with the user's authentication token. Here is what I came up with: import axios from "axios"; c ...

Encountered error message: "Cannot assign argument of type '() => () => boolean' to parameter of type 'EffectCallback'"

I recently started working with TypeScript. I encountered an issue when attempting to utilize useEffect in TypeScript within a React context, Error: Argument of type '() => () => boolean' is not assignable to parameter of type 'Effec ...

Ensure that all items retrieved from the mongoDB query have been fully processed before proceeding further

In the midst of a challenging project that involves processing numerous mongoDB queries to display data, I encountered an issue where not all data was showing immediately upon page load when dealing with large datasets. To temporarily resolve this, I imple ...

Essential front-end tools for enhancing Angular 2 projects

Hi there! I specialize in Laravel development and am currently diving into the world of Angular 2 framework. Up until now, I've been handling my third-party front end assets through bower, using a bower.json file to manage dependencies. Check out a sn ...

Always deemed non-assignable but still recognized as a universal type?

I'm curious about why the never type is allowed as input in generic's extended types. For example: type Pluralize<A extends string> = `${A}s` type Working = Pluralize<'language'> // 'languages' -> Works as e ...

Angular ngx-translate Feature Module failing to inherit translations from Parent Module

Currently, I am implementing lazy loading for a feature module. I have imported TranslateModule.forChild() with extend true to load feature-specific translations. In my app.module, I am importing TranslateModule.forRoot to load common translations. The i ...

Arranging Angular Cards alphabetically by First Name and Last Name

I am working with a set of 6 cards that contain basic user information such as first name, last name, and email. On the Users Details Page, I need to implement a dropdown menu with two sorting options: one for sorting by first name and another for sorting ...

Encountering a 404 error when trying to deploy an Angular application

After following the Angular documentation for deployment, I am deploying my angular application on github pages. The steps I have taken include: 1. Running "ng build --prod --output-path docs --base-href /<project_name>/". 2. Making a copy of docs/ ...

typescript Can you explain the significance of square brackets in an interface?

I came across this code snippet in vue at the following GitHub link declare const RefSymbol: unique symbol export declare const RawSymbol: unique symbol export interface Ref<T = any> { value: T [RefSymbol]: true } Can someone explain what Re ...

What is an alternative way to confirm the invocation of a service method in Jasmine unit testing for Angular without relying on spyOn?

In my Angular project, I have a method named performAnalytics() within a service called analyticsService. This method is triggered when a specific element in the HTML is clicked. As part of writing unit test cases using Jasmine, I'm trying to ensure t ...