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

What is the best way to prevent users from entering a zero in the first position of a text box using JavaScript

Although I am aware this may be a duplicate issue, the existing solution does not seem to work for me. The field should accept values like: valid - 123,33.00, 100,897,99, 8000 10334 9800,564,88.36 invalid - 001, 0 ...

What is the best way to design functions that can return a combination of explicit types and implicit types?

When looking at the code provided below, function system(): ISavable & ISerializable { return { num: 1, // error! save() {}, load() {}, serialize() {}, deserialize() {}, } } interface ISavable { sa ...

Is it necessary to have a premium firebase/firestore account in order to set up stripe payments?

When learning how to integrate Stripe payments with Angular and Firebase, make note that a paid Firebase account is required for the cloud function to work. External API requests are blocked on the free "Spark" plan. ...

What is the method for dynamically assigning a name to ngModel?

I have the following code snippet: vmarray[]={'Code','Name','Place','City'} export class VMDetail { lstrData1:string; lstrData2:string; lstrData3:string; lstrData4:string; lstrData5:string; ...

Unused Angular conditional provider found in final production bundle

Looking for a way to dynamically replace a service with a mock service based on an environment variable? I've been using the ?-operator in the provider section of my module like this: @NgModule({ imports: [ ... ], providers: [ ... en ...

The error message you are encountering is: "Error: Unable to find function axios

Can't figure out why I'm encountering this error message: TypeError: axios.get is not functioning properly 4 | 5 | export const getTotalPayout = async (userId: string) => { > 6 | const response = await axios.get(`${endpoint}ge ...

Using the <template> syntax to apply ngclass or [class.classname]

I am familiar with the syntax for ngFor, ngIf, and ngSwitch using templates. Can someone provide guidance on how to utilize ngClass or [class.className] with template syntax in Angular 2? Can anyone explain how to implement classes using template syntax i ...

How can we properly retrieve data in order to update the user interface using the useEffect hook and useState in React

I'm diving into the world of Next.js 13 for the first time, attempting to retrieve a cart object from the API and display it on the UI. Utilizing useState to hold the cart object and useEffect to fetch it. However, upon calling setCart(), the UI fail ...

Tips for utilizing Variant on an overridden component using as props in ChakraUI

I created a custom Component that can be re-rendered as another component using the BoxProps: export function Label ({ children, ...boxProps }: BoxProps) { return ( <Box {...boxProps}> {children} </Box> ); } It functio ...

Exploring the capabilities of Angular2 and Jasmine through testing

I have been working on a basic spec for a component and I'm curious about the test's behavior. The test is designed to verify if a component is successfully created. It seems that when the test is executed, it first compiles and runs the Compone ...

Could you clarify the significance of the brackets in this TypeScript Lambda Expression?

I'm currently delving into an Angular book, but I'm struggling to locate any definitive documentation regarding the usage of square brackets in a lambda expression like [hours, rate]) => this.total = hours * rate. While I grasp that these para ...

Tips on organizing a typescript object/StringMap in reverse order to prioritize the last element

I've just started working with TS/React in a .tsx file and I'm trying to add a key/value pair to a StringMap at the very first index. Below is the code snippet that: takes the StringMap 'stats' as input, iterates through each row, re ...

Running `ng start angularProject` or `npm install` will generate additional files in the project's

I'm encountering a major issue where every time I create a new project using 'ng start' or run 'npm install', extra files are being generated in the root folder like this. https://i.stack.imgur.com/BUphZ.png Here is my package.js ...

How can I customize the styling of Angular Material Datepicker?

I am currently incorporating the Angular Material Datepicker into various parts of my application. One particularly important usage is a legacy one that must remain untouched for the proper functioning of the application. This legacy Datepicker is extensiv ...

Issue with recognition of function in Angular2 component

I have been working on creating a separate component for presenting a news feed. Initially, everything worked fine when the code was within app.component.ts. However, after separating the code into its own component (news-feed.component.ts), I encountered ...

Having trouble with the lodash find function in my Angular application

npm install lodash npm install @types/lodash ng serve import { find, upperCase } from 'lodash'; console.log(upperCase('test')); // 'TEST' console.log(find(items, ['id', id])) // TypeError: "Object(...)(...) is un ...

An error is triggered by the EyeDropper API stating that 'EyeDropper' has not been defined

I am trying to utilize EyeDropper for an eyedropper function in my project that uses Vue2 + Ts. Here is the code snippet: <div v-if="haveEyeDropper" @click="handleClickPick" > <i class="iconfont icon-xiguan"> ...

A custom function that changes the state of a nested object using a specified variable as the key argument

My goal is to update the state of an object using a function called updateDatas. This function takes the arguments key, possibly subKey, and value. interface Datas { code: number; item1: Item; } interface Item { id: number; name: string; } const ...

Is it possible to designate a Typescript generic type as a tuple with equal length to that of another tuple?

Imagine having a function that takes in a dataset which is an array of (identically-typed) tuples: type UnknownTuple = any[] function modifyDataStructure<T extends UnknownTuple>(list: T[]) { ... } The goal is to define a second argument with the ...

Application fails to launch after disabling unsafe-eval in the restricted Content Security Policy settings

Description My application is facing issues due to having a restricted CSP policy that does not allow unsafe-eval for scripts. When I add a Content-Security-Policy header without unsafe-eval, my application fails to load. Minimal Reproduction The restric ...