How can we update the information in the initial observable using data from a separate observable, taking into consideration specific conditions in Angular with RxJS?

Encountered a scenario where I need to fetch data from an API (e.g. cars via getCars()) that returns Observables and then get additional data by car model (e.g. features via getFeatures(model)) in order to replace the features data for each car.

In relation to this, how can we incorporate a conditional operator to trigger a request for getFeatures(...) only when the model is 'porsche'?

this.getCars().pipe(
 map(cars => {
 ...
}))
.subscribe(cars => {})

export interface Car {
   id: string,
   model: string,
   engine: string,
   details: Detail[]
}

export interface Detail {
   features: string[]
   ...
}

If you have any insights or ideas on this matter, please feel free to share them. Your assistance would be greatly appreciated. Thank you in advance :)

Answer №1

let cars$ = getCars();
let carsWithFeatures$ = cars$.pipe(
  map((cars) =>
    cars
      .filter((car) => car.model === 'porsche')
      .map((car) =>
        getFeatures(car.model).pipe(map((features) => ({ ...car, features })))
      )
  ),
  mergeMap((cars$) => forkJoin(cars$))
);
  • Utilizing JS array filter to only keep Porsche cars
  • Employing JS array map to request feature information for each Porsche in the list
  • Merging the features data with each corresponding Porsche entry (model has been simplified)
  • Using mergeMap and forkJoin to combine the elements into a single object for emission by carsWithFeatures$

Check out Stackblitz for more details: https://stackblitz.com/edit/rxjs-drukvp

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

Inferencing partial types in Typescript

I'm completely stuck on this and can't seem to figure it out without using a second function: interface Fixed { a: number } const fn = <A, B extends {} = {}>(b: B) => { return b } fn({ a: 1 }) // { a: number } fn<Fixed>({ a: 1 } ...

how to retain the state value as a number and enable decimal input in a TextField component in React

Currently working on a project using React, Material UI, and TypeScript. I need to enable decimal values in a TextField while ensuring that my state value remains a number type instead of a string. export default function BasicTextFields() { const [value ...

How to successfully extract and understand JSON data in Angular that has been delivered from a Spring controller

I am facing a unique challenge while trying to utilize JSON data obtained from a Spring API to populate a list in Angular. Within the datasets-list.component.ts file, I have the following code: import { Component, OnInit } from '@angular/core'; i ...

Is there cause for worry regarding the efficiency issues of utilizing Object.setPrototypeOf for subclassing Error?

My curiosity is piqued by the Object.setPrototypeOf(this, new.target.prototype) function and the cautionary note from MDN: Warning: Modifying an object's [[Prototype]] is currently a slow operation in all browsers due to how modern JavaScript engines ...

Transforming res.json() into an Array of Objects

I am dealing with a Java webservice that outputs a list of Json objects with specific properties: public class Oferta { private int id; private String categoria; private String descricao_oferta; private String anunciante; private double valor; private boo ...

Getting the Most Out of .find() in Angular 4

Despite reading various similar questions, I'm still struggling to make the .find() function work in my application. I have a service with the following API: export class VehicleService { private defUrl = 'API'; constructor(private ht ...

A guide on validating an array of literals by leveraging the power of class-validator and class-transformer through the methods plainToInstance or plainTo

I am struggling with my validation not working properly when I use plainToInstance to convert literals to classes. Although the transformation appears to be successful since I get Array(3) [Foo, Foo, Foo] after using plainToInstance(), the validation does ...

TSLint Alert: Excessive white space detected before 'from' keyword (import-spacing)

I'm currently using WebStorm and working to maintain a specific code style: However, I encounter an issue where TSLint highlights my spacing and provides the following hint: "Too many spaces before 'from' (import-spacing)". My main ques ...

Having trouble creating a component in Angular 6.1.1 that includes both inline template and inline styles

After setting up Angular6 on my Ubuntu-18 machine, I decided to initiate a project using the command ng new project --routing, Next, I attempted to create components with inline styles and templates. To do this, I used the command ng g c microsoftroute - ...

Validate that a string is a correct file name and path in Angular without using regular expressions

Currently, I am using regex to determine if a string is a valid file name and path. However, when the string length becomes longer, it ends up consuming a significant amount of CPU, resulting in browser performance issues. public static readonly INVALID_F ...

An issue arising with the TypeScript antlr4ts listener type

I am currently attempting to incorporate the antlr4 parser into an angular project. Within a dataservice class, there is a function being called that appears as follows: parseRule() { const ruleString = ' STRING TO PARSE'; const inputS ...

Is Angular Template Polymorphism Failing?

So I'm working with a base class that has another class extending it. export class Person { public name: string; public age: number; } export class Teacher extends Person { public yearsTeaching: number; } Now, in my component, I need to ...

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

Issue with uploading video files using ng2-file-upload in Angular7 and ASP .Net Core 2.1

While working on my project, I encountered an issue with uploading video files using ng2-file-upload to the server. The photo upload functionality is working fine, but when attempting to upload a video file larger than 27MB, the process gets canceled autom ...

When selecting a MenuItem, only a ReactOwner has the ability to add a ref using addComponentAsRefTo(...)

I'm currently working on a basic component that looks like this: class App extends React.Component<{}, {}> { constructor() { super(); } render() { return ( <MuiThemeProvider muiTheme={muiTheme}> <div> ...

Exploring TypeScript Module Importation and WebPack Integration

Struggling with WebPack's injection of imported dependencies for a TypeScript project. The first challenge is getting TypeScript to recognize the imported module. In the header.ts file, there is a declaration of a module nested under vi.input, export ...

Excessive geolocation position responses in Angular 5

I am trying to implement an Angular 5 component that will continuously fetch my current location every 3 seconds if it has changed. Here is a snippet of my code: export class WorkComponent implements OnInit { constructor(private userService: UserService ...

Issue with type narrowing and `Extract` helper unexpectedly causing type error in a generic type interaction

I can't seem to figure out the issue at hand. There is a straightforward tagged union in my code: type MyUnion = | { tag: "Foo"; field: string; } | { tag: "Bar"; } | null; Now, there's this generic function tha ...

There was a TypeScript error found at line 313, character 9 in the file @mui/material/styles/experimental_extendTheme.d

Encountering Typescript error while using Material UI component for date range picker Link - https://mui.com/x/react-date-pickers/date-range-picker/ Snippet of the code import * as React from 'react'; import { Dayjs } from 'dayjs'; im ...

Unable to modify the Jest mock function's behavior

The issue I am facing involves the following steps: Setting up mocks in the beforeEach function Attempting to modify certain mock behaviors in specific tests where uniqueness is required Encountering difficulty in changing the values from the in ...