Merge ObjectA emissions with ObjectB Array using RxJS

Currently, I have a code snippet that pulls data from a web service:

@Effect()
searchAction$ : Observable<Action> = this._actions$
    .ofType(ActionTypes.SEARCH_CASES)
    .do(val => this._store.dispatch(new SetLoadingAction(true)))
    .map(action => action.payload) // only interested in the payload
    .map(payload => new CaseSearchCriteria(payload)) // create search criteria
    .switchMap(payload => this._httpSearchCases.searchDiseaseCases(payload)
        /*
            1. The return from httpCall is IDiseaseControlCaseManagement[]
            2. Transform this array into SearchDiseaseCaseResults[]
         */
        .do((val) => {
            console.log('Type of Value: ', typeof val);
            console.log('Is value SearchDiseaseCaseResult? :', val instanceof SearchDiseaseCaseResults);
        })
        .map(res => new LoadSearchResultsAction(res))
    );

I have included comments to briefly explain the desired functionality, and while I am certain there is a ReactiveX operator that can achieve this, I have been unable to identify it.

I attempted to use the .scan operator by pushing to the accumulator:

.scan((acc: SearchDiseaseCaseResults[], val: IDiseaseControlCaseManagement) => {
            acc.push(new SearchDiseaseCaseResults(val));
        })

However, TypeScript static analysis indicates that this approach is incorrect:

Error:(32, 31) TS2453:The type argument for type parameter 'R' cannot be inferred from the usage. Consider specifying the type arguments explicitly.


Type argument candidate 'SearchDiseaseCaseResults[]' is not a valid type argument because it is not a supertype of candidate 'void'.

Therefore, I require an operator chain (or method) that will enable me either to:

  1. Receive an emission of type ObjectA.
  2. Transform the emission of type ObjectA into an object of type ObjectB.
  3. Receive emissions of type ObjectB.
  4. Combine each emission of ObjectB into a single array ObjectB[].

or

  1. Receive an emission of type ObjectA[].
  2. Transform the emission of type ObjectA[] into an array of type ObjectB[].

Answer №1

It seems like what you're looking for is the map operator in this scenario.

Let's shift our focus to your switchMap function.

.switchMap(payload => this._httpSearchCases.searchDiseaseCases(payload)

         //    1. Return from httpCall is IDiseaseControlCaseManagement[]
        .map(IDiseaseControlCaseManagementArray => this.mapToSearchDiseaseCaseResultsArray(IDiseaseControlCaseManagementArray) )

        .do((val) =>{
            console.log('Type of Value: ', typeof val);
            console.log('Is value SearchDiseaseCaseResult? :', val instanceof SearchDiseaseCaseResults);
        })
        .map(res => new LoadSearchResultsAction(res))
    );

I believe that covers your question about the implementation of the

mapToSearchDiseaseCaseResultArray
method.

If mapping a single IDiseaseControlCaseManagement to a SearchDiseaseCaseResult is feasible, then extending it to arrays should be straightforward.

Assuming there's a convertFrom method available:

searchDiseaseCaseResult = convertFrom(iDeseaseControlCaseManagement)

For arrays:

mapToSearchDiseaseCaseResultArray(sourceArray) {
  return sourceArray.map(caseManagement => this.convertFrom(caseManagement));
}

You'll still need to define the convertFrom method for individual items, but once that's done, you can integrate it as shown above.

Does this explanation make sense?

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

Is it possible to wait for the conversation to be updated within the Microsoft Bot Framework?

After successfully creating a chatbot for Messenger, I decided to develop my own interface. However, I encountered some challenges with managing the replies. Despite using the Microsoft BotFramework and being able to send and receive messages, I struggled ...

Body element in Angular component seems to be mysteriously added at the bottom

<pI'm experiencing something unusual. Every time I render my custom element, the content of the body (innerHTML) of the element is getting appended at the end.</p> <pHere's an example on my homepage - notice how 'childbody' ...

Navigating an immutable list to make updates to its values

Within this list, I have an unalterable group of objects. My task is to change the value of the 'isReq' property to false for all objects except the one with the id 2. [ { 'id': 1, 'name': 'Ram', 'D ...

Securing redirection in WebPart using Azure AD: Best practices

I've successfully created a Sharepoint Webpart with a straightforward goal: authenticate users on an external website embedded within Sharepoint. This external site utilizes Azure AD for user logins. However, my current implementation has a significa ...

Having trouble implementing a custom pipe on high chart tooltip values

I'm currently working on integrating a tooltip for whisker boxplot charts in Highcharts within my Angular 4 application. I've created a custom pipe to convert numbers in thousands to 100K, and millions to 100M, etc. However, when trying to apply ...

What could be causing my matDialog to display incorrectly in Angular version 15?

After I upgraded my project to version 15 of Angular, following the official Angular documentation, I encountered an issue with my MatDialog not opening correctly. The problem seemed to stem from removing the entryComponents and transforming all components ...

I am experiencing an issue with my service provider when it comes to displaying multiple navigator stacks

Currently, I am developing a provider to manage the user's state across different views. The primary function of this provider is to display either one stack navigator or another based on whether a certain variable is filled or empty. This setup allow ...

Tips for incorporating attributes into a customized Material-UI props component using TypeScript in React

I'm interested in using material-ui with react and typescript. I want to pass properties to the components, but I'm having trouble figuring out how to do it. Currently, I'm working with the react-typescript example from the material-UI repos ...

Error encountered: JSON.parse failed due to unexpected input at position 281

I've been struggling to find a solution, as my searches always turn up irrelevant answers. I hope someone can help me out with this issue. Thank you in advance for your assistance. TypeError: JSON.parse Error: Unexpected token at position:281 imp ...

The JavaScript function for converting a date to a local string in the format of DD MMM YYYY is causing an error message in the browser console stating that it is not a valid function

I am encountering an issue with formatting a date string. The date is currently in the format 2021-03-31T00:00:00, and I need it to be displayed as 31 Mar 2021. In my TypeScript code, I attempted to use the following function: const formattedDate = i.Susp ...

How can I display a new module in Angular without navigating to it?

After following the tutorial at https://angular.io/guide/lazy-loading-ngmodules#create-a-feature-module-with-routing I set out to create the following: My goal is to have a dedicated module for all customer-related components accessible through the /cust ...

Combining Django Rest Framework API with Angular 2 for seamless integration

Currently, I am working on building a back-end API using Django Rest Framework and a front-end using Angular 2. The Django server is running on localhost:8000 and the Angular server on localhost:3000. However, I am encountering an error when trying to acce ...

What is the best method for calculating the total of a column field within an array in Angular 9.1.9?

I am using Angular 9.1.9 and Html to work with a nested array field in order to calculate the total sum and display it in a row. Within my array list ('adherant'), I am aiming to sum up a specific column's values ({{ Total Amount }}) and pr ...

Errors related to Angular StaticInjector for the classes Location, LocationStrategy and PlatformLocation

I have developed a versatile npm module that is compatible with any Angular 5 application. The shared module includes a universal service that utilizes Location injection. Here is an outline of the global service: global.service.ts import {Location} from ...

Tips for utilizing chodorowicz / ts-debounce effectively

Looking to utilize the debounce function provided by the ts-debounce package (available at here) in my typescript project. However, struggling to find a concrete example of its usage in typescript. Would greatly appreciate any help or guidance on this ma ...

How can I efficiently map an array based on multiple other arrays in JavaScript/TypeScript using ES6(7) without nested loops?

I am dealing with 2 arrays: const history = [ { type: 'change', old: 1, new: 2 }, { type: 'change', old: 3, new: 4 }, ]; const contents = [ { id: 1, info: 'infor1' }, { id: 2, info: 'infor2' }, { id: ...

Tips for implementing page-break-after:always within a bootstrap row?

I have a bootstrap row with a set of divs inside like this: @media print { p { page-break-after : always } } <div class = "row"> <div> data1 </div> <p> break page here </p> <div> data2 </div> <div> ...

Mistakes in Compiling Typescript Code in Angular 2

Currently, I am utilizing Visual Studio 2017 for the development of an Angular 2 application with an Asp.Net Core WebApi backend. My guide through this process is the ASP.NET Core and Angular 2 Book authored by Valerio De Sanctis. Initially, everything was ...

Exploring the versatility of Angular Material classes beyond the boundaries of traditional Angular

We have embarked on the reconstruction of our web application and opted for Angular as our frontend framework, with Google Material as our primary style concept due to its simplicity and popularity. While most of our pages will be part of the Angular appl ...

Custom Validation requires promises to be present

Creating a custom validation method to validate ranges can be done in different ways. Below is an example of how to achieve this: static ratingRange=(min:number,max:number) => { return (control:AbstractControl):Promise<ValidationErrors|null&g ...