Combining portions of objects in Angular2

I want to combine two identical type observables in Angular2 and return an observable of the same type in a function.
My goal is to:

transform this setup:

obs1.subscribe(obs => console.log(obs))
(where I receive): 
{
   count: 10,
   array: <someObservable[]> 
}

and

obs2.subscribe(obs => console.log(obs))
(where I get): 
{
   count: 10,
   array: <someObservable[]> (different objects)
}

into:

{
   count: 10 (always the same number),
   array: <combined array from obs1 and obs2>
}

How can I achieve this easily? (It might be simple for junior level angular developers, but as a newbie in this field, I need to do it quickly). Thanks in advance.

---UPDATE---

considering this code snippet :

const obs2 = obs1.pipe(
        switchMap(value => {
          return this._loadMoreTextSearchSub.asObservable()
          .pipe(pairwise(),
          map(params => this.getPagingParameters(params[0], params[1])),
          switchMap(request),
          map(response => response.packages),
          scan<SearchPackage[]>((all, current) => {
            return [...all, ...current];
          }, 
          value.packages
          ));
        }))
        .subscribe(data => console.log('sec', data));

It returns an array of objects. How can I encapsulate that array within an object and add an extra property - 'count'?

Current:
[{...}, {...}, {...}, {...}]
Desired:
{count: some_number, array: [{...}, {...}, {...}]}

Answer №1

If you find yourself needing to make subsequent calls to Observables, you can utilize the mergeMap() operator.

For example, let's consider calling obs1 first, obtaining the result of obs1, then calling obs2, and finally combining both results before returning them.

obs1.pipe(mergeMap((firstResult) => {
    return obs2.pipe(map((secondResult) => {
        return { count: firstResult.count, array: [...firstResult.array, ...secondResult.array] };
    }))
})).subscribe((data) => {
    console.log(data);
})

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

Angular-cli and Chrome extension compatibility causing unexpected UI problems post-build

I developed an application with a sticky header at the top using angular2 mdl layouts. Recently, I made changes to the code to create a more customizable header. However, after building the app (ng build) and importing it as an unpacked extension, the con ...

Remove validators from an Angular formArray

Is there a way to reset validators for the formArray within my formGroup? Check out my StackBlitz for reference. .ts this.createEstimation = this.fb.group({ name: ['', Validators.required], surname: ['', Validators.required], ca ...

What is the proper way to employ if and else if statements within Angular2?

Here's a question that has been duplicated on my How to utilize *ngIf else in Angular? post! ...

An object that appears to be empty at first glance, but contains values that are undefined

I am facing an issue with my object that I am populating with information. The logs show the object as empty, but when I inspect it in Chrome, it appears to have the correct details filled in. Here is a snapshot of what the logs display: closed: closed o ...

A new issue arises after merging in Google Datastore, as an unexpected property is

Currently, I am working on developing an API in Typescript to interact with a Google Cloud Datastore instance for storing and retrieving entities. So far, I have successfully implemented the GET, POST, and DELETE methods. However, I encountered an issue w ...

``There seems to be an issue with Angular2 routing not functioning properly due to the presence of

Seeking assistance with an issue I'm facing. I am attempting to pass parameters in routing. However, when my parameter contains a slash symbol, Angular interprets the text after the slash as another parameter, causing my routing to fail. { path: &ap ...

What is the process for sending an http get request that provides a JSON array to populate an ngFor directive?

I'm trying to figure out how to make an http get request in order to retrieve a json array of data that I can use within an ngFor loop. The list that needs to be looped through is stored in this.list. Currently, the json file for testing purposes is l ...

Associate keys with strings and then map them to a specific type of strings in Typescript

I am endeavoring to develop a React component that extends the Octicons icon library available from Github at @githubprimer/octicons-react. One of the components exported by the library is the iconsByName type, which has the following structure: type ico ...

"Embracing the power of multiple inheritance with Types

I am struggling with the concept of multiple inheritance in TypeScript. It doesn't make sense to overload a hierarchy with too much functionality. I have a base class and several branches in the hierarchy. However, I need to utilize mixins to isolate ...

Encountering type-checking errors in the root query due to the specific types assigned to my root nodes in a GraphQL and TypeScript application built using Express

As I delve into the world of typescript/graphql, I encountered a peculiar issue while trying to define the type for one of my root nodes. The root node in question simply fetches a user by ID in the resolve function, and thus, I assigned the 'type&apo ...

Transferring information to an Ionic 5 custom element label

In my ionic 5 app, I have a side menu and tabs. Each page can have different contents for the side menu and the tabs. Instead of duplicating the ion-menu in each page, I created a header component (and one for the tabs) as follows: HEADER COMPONENT: <i ...

Utilize the useState() hook to add an object and display its data in a React Native

Here is a function I am working with: const [dataLoc, setDataLoc] = useState({date: "No data received yet from sensor", coords: {}}); This is where I set the location: Geolocation.getCurrentPosition( location => { const date = d ...

Encountering an Issue with Vue 3 and Vue Router 4: Uncaught TypeError - Trying to Access Undefined Properties (specifically 'push')

I'm currently working with Vue 3, Vue Router 4, and TypeScript in my project. However, I've encountered an issue while trying to utilize router.push(). Every time I attempt this, I receive a console error stating: Uncaught (in promise) TypeError: ...

Sending an array of dates from Angular to Java - A quick guide

I'm facing an issue where Java is interpreting date attributes as null objects when I send an array of objects with date attributes from Angular to a Spring REST API. How can I ensure that the values are passed correctly? While researching, I came ac ...

No recommended imports provided for React Testing Library within the VS Code environment

I am currently in the process of setting up a Next JS project with Typescript integration and utilizing React Testing Library. Unfortunately, I'm facing an issue with getting the recommended imports to work properly within my VS Code environment. To i ...

Exploring the way to reach a specific page in Ionic3

Is there a way to navigate from a child page back to its parent page without the URL getting messed up? It seems like when I try to do this, the child remains unchanged while only the parent page updates. If this is correct, how can I remove the child fr ...

Child component in Angular 2 that verifies the parent component

My goal is to have a component behave differently depending on its parent component. For example, in the scenarios below, the child component would exhibit slightly different behavior. Scenario A <parent-a> <child></child> </parent-a ...

Transforming JSON keys in Angular

As a newcomer to angular and API integration, I am facing an issue with ngCharts in my project. The chart specifically requires the keys names in JSON to be "value" and "name", but the API I am using provides keys named "count" and "label". Is there a way ...

Guide on linking an XML reply to TypeScript interfaces

Currently, I am faced with the task of mapping an XML response (utilizing text XMLHttpRequestResponseType) from a backend server to a TypeScript interface. My approach has been to utilize xml2js to convert the XML into JSON and then map that JSON to the Ty ...

Angular v15 Footer Component Table

In my Angular 15 project, I am attempting to correctly position and utilize the mat table with the following code snippet: <tr mat-footer-row *matFooterRowDef="displayedColumns"></tr>. While the displayedColumns property is functionin ...