Inject the data within Observable<Object> into Observable<Array>

I'm faced with a situation where I have two distinct API endpoints. One endpoint returns a single Card object, while the other endpoint returns an Array of Card objects. My goal is to retrieve the first Card from the single Card endpoint and place it at the beginning of the Array obtained from the second endpoint. I'm wondering if there's a way to achieve this. Both endpoints return observables from HTTPClient, so I'm thinking there might be a straightforward solution using operators, but I'm not quite knowledgeable enough to implement it yet. To provide a clearer example:

Current configuration:

latestCards$: Observable<Cards> = http.get('latestCardsEndpoint');
// { title: 'Latest', cards: [], ... }  

featuredCards$: Observable<Cards[]> = http.get('featuredCardsEndpoint');
// [
//   { title: 'Featured1', cards: [], ... }, 
//   { title: 'Featured2', cards: [], ... },
//   ...
// ]

Desired outcome:

homeCards$: Observable<Cards[]>;
// [
//   { title: 'Latest', cards: [], ... },
//   { title: 'Featured1', cards: [], ... },
//   { title: 'Featured2', cards: [], ... },
//   ...
// ]

Answer №1

No problem:

Simple solution:

import {combineLatest} from 'rxjs/observable/combineLatest';
import {map} from 'rxjs/operators';

homeCards$= combineLatest(latestCards$,featuredCards$).pipe(
  map(([latest,feature]=>[latest,...feature])
);

There is a drawback with this method: it requires both requests to finish before emitting any values.

Another simple solution:

import {forkJoin} from 'rxjs/observable/forkJoin';
import {map} from 'rxjs/operators';

homeCards$= forkJoin(latestCards$,featuredCards$).pipe(
  map(([latest,feature]=>[latest,...feature])
);

Similar to the previous approach, it also waits for both streams to emit once. This is because they are http observables, which emit one response and then complete.

An improved solution:

If the latestCard$ request has a quicker response time, use it as the initial result and fetch the remaining data in the background.

import {merge} from 'rxjs/observable/merge';
import {of} from 'rxjs/observable/of';
import {mergeMap, map}from'rxjs/operators';

homeCards$= latestCards$.mergeMap(latest => {
            const fullResult$ = featuredCards$.map(featured => [latest,...featured]);
            return merge(of([latest]), fullResult$);
            });

Answer №2

If you're looking to tackle this issue, one approach could be as follows:

Observable
    .combineLatest(latestCards$, featuredCards$) // generates an array of responses
    .map(([latestCard, featuredCards]) => [latestCard, ...featuredCards])
    .subscribe(// handle your tasks)

Take a look at this demonstration on jsfiddle: http://jsfiddle.net/foxfghhn/

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

Passing an array from a parent component to a child component in Angular

Just to give you some background, I only started my Angular learning journey about a week ago, so feel free to start from the very beginning. So, how can this be achieved? Inside app.component.ts, there is a standard array that needs to be accessible by m ...

What is the best way to connect to a library using a script within a Typescript React application?

I'm a newbie to React and haven't worked on web development in years, so I'm facing a basic issue: Currently, I'm working on implementing a Stripe-based payment flow in a React web app (written in Typescript) and I've hit a roadbl ...

How can I effectively build an Angular Library containing various components?

I am currently restructuring the core elements that form a search page into an angular library. My goal is to include various components in this angular library, such as SearchControls, PageHeader, PageFooter, and more. I intend to insert <search-contro ...

PlatypusTS: Embracing Inner Modules

Incorporating angular, I have the capability to fetch object instances or import modules using the $injector in this manner: export class BaseService { protected $http: angular.IHttpService; protected _injector: angular.auto.IInjec ...

Strategies for increasing the number of images in Angular

At the start, 15 images are displayed from the API. However, the "Get dogs" button should load an additional 15 images each time it's clicked, but currently, it doesn't work. How can we fix this issue? http.service.ts - a service that interacts ...

Error: Unable to use import statement outside of a module when deploying Firebase with TypeScript

Every time I try to run firebase deploy, an error pops up while parsing my function triggers. It specifically points to this line of code: import * as functions from 'firebase-functions'; at the beginning of my file. This is a new problem for me ...

Can you explain the significance of "Result" in the .map operator of an Observable fetched from an http.get call in NativeScript with Angular?

I'm currently working on the Nativescript/Angular tutorial and I stumbled upon a particular piece of code that has left me puzzled. In chapter 4 (Nativescript modules), there is a section where they make an http.get request to fetch the Grocery List a ...

Update the AngularJS (1.5) application to Angular 5

Looking for advice on transitioning an AngularJS app to Angular (in this case, version 5). I've been exploring the official documentation, but I still have some uncertainties. From what I gathered in the guide, it suggests migrating from AngularJS by ...

The attribute 'attribs' is not found on the 'Element' type in cheerio

When I run my code, I encounter an error that says Property 'attribs' does not exist on type 'Element'. It's puzzling to me why this error is being thrown. After examining the type definitions of cheerio, I discovered that attribs ...

Dialog box obscuring PrimeNG dropdown menu

I'm working on an Angular2 app that utilizes PrimeNG components. My issue arises when trying to include a dropdown inside a dialog box. Despite my implementation, the dropdown ends up being cut off due to the constraints of the dialog box, as visible ...

What could be causing the lack of updates for my service on the app component?

I am currently using Ionic 4 and facing an issue with displaying information about the logged-in user. The code works perfectly in all components except for the app component. I have a variable named userData which is a BehaviorSubject. Can someone help me ...

Angular allows for routing two distinct paths to separate components located within the same lazily loaded submodule

There are two paths available: /a and /b Both routes lead to the same child module in the parent module: // app-routing.module.ts { path: 'a', loadChildren: () => import('./m-child/m-child.module').then(m => m.ChildModu ...

Detecting changes in Angular2 through a commonly shared service

I have a parent function called ngOnInit() that retrieves value from Google Maps as shown below: instance.input = document.getElementById('google_places_ac'); autocomplete = new google.maps.places.Autocomplete(instance.input, { types: [& ...

Tips for resolving SyntaxError: Unable to utilize import when integrating Magic with NextJS in a Typescript configuration

Looking to integrate Magic into NextJS using TypeScript. Following a guide that uses JavaScript instead of TypeScript: https://github.com/magiclabs/example-nextjs Encountering an issue when trying to import Magic as shown below: import { Magic } from &qu ...

Angular-cli working in conjunction with an express project

I am currently working on a project that involves Express, MongoDB, and the REST API. I now want to integrate Angular into the project using angular-cli. However, I have several questions about the process. Here is the current structure of my project: htt ...

Tips for adjusting the radio button value similarly to a checkbox in Angular 2 using *ngFor

my checkbox and radio button implementation: <input id="{{k.group_name}}_{{i}}" name="{{k.group_name}}" type="checkbox" class="hide" name="{{k.group_name}}" [value]="m.details" (change)="change($event, m , k.item_ingredient_group_key,false,k.maximum)"& ...

What is the process of integrating an API key into Apollo-Angular in order to retrieve information from the MongoDB Realm GraphQL API?

I have been utilizing the MongoDB realm GraphQL API to retrieve data, while also using Apollo-Angular. However, in order to access the data through the GraphQL API, an API key is required. I have successfully tested this by using Postman and including the ...

Replace pipeline function during component testing

During my unit testing of a component that utilizes a custom pipe, I encountered the need to provide a fake implementation for the transform method in my test. While exploring options, I discovered that it's feasible to override components, modules, ...

How to access the types of parameters in a function type

I am working on a function that takes a value and default value as arguments. If the value is a boolean, I want the return type to match the type of the default value. Here is the function I have: export type DetermineStyledValue<T> = ( value: str ...

Inserting items into an array entity

I am attempting to insert objects into an existing array only if a certain condition is met. Let me share the code snippet with you: RequestObj = [{ "parent1": { "ob1": value, "ob2": { "key1": value, "key2": va ...