Managing situations within the RxJS pipeline

I have an Observable called leadChanged$, which I can easily connect to the template using the async pipe.

leadChanged$: Observable<LeadModel>;

this.leadChanged$ = this.leadsDataService.leadChanged$.pipe(
          map((res) => ({
            ...res,
            alert: { ...res.alert, transcript: highlightKeywordsLeadFunction(this.lead) },
          }))     
        );

However, there is additional logic now where I need to handle the situation when res?.isManualLead is present. Is it possible to achieve this without using a subscribe method? I still want to continue utilizing the async pipe in this case.

leadChanged: LeadModel;

this.leadsDataService.leadChanged$
      .subscribe((res) => {
        if (res?.isManualLead) {
          this.leadChanged = {
            ...res,
          };
        } else {
          this.leadChanged = {
            ...res,
            alert: { ...res.alert, transcript: highlightKeywordsLeadFunction(this.lead) },
          };
        }
      });

Answer №1

Is it possible to incorporate a condition within the map operator?

this.leadChanged$ = this.leadsDataService.leadChanged$.pipe(
  map(res => res?.isManualLead
    ? { ...res } 
    : { ...res, alert: { ...res.alert, transcript: highlightKeywordsLeadFunction(this.lead) } }
  ),
);

Answer №2

Decide whether to subscribe to the first or second observable based on a condition using the iif operator in RxJS.

import { iif, of } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
...

this.dataService.dataChanged$.pipe(
  mergeMap((res) => iif(() => res?.conditionIsMet, of({ ...res }), of(anotherValue)))
);

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

Tips for obtaining the accurate HTML code format using Angular 2's input feature:

I am looking to retrieve all the code with an input as [input] and a tag as #tag. When attempting to obtain HTML code with jQuery using console.log($("#content")[0].outerHTML);, this is an example of how the code looks: <div dnd-droppable [dropZones]= ...

Combining Two Dropdown Selections to Create a Unique Name using Angular

I am facing a challenge with 2 dropdown values and input fields, where I want to combine the selected values from the dropdowns into the input field. Below is the HTML code snippet: <div class="form-group"> <label>{{l("RoomType")}}</labe ...

What is the reason behind the failure of a react factory method compilation when extending a typescript class, despite it working perfectly fine on the base class?

As I delve into my lengthy codebase consisting of hundreds of lines, I have managed to narrow down my issue to a concise example. My query pertains to the peculiar behavior exhibited by the Typescript compiler in a specific scenario. The snippet below com ...

I encountered a typescript error while trying to export my Class component within a Higher Order Component (HOC)

I'm encountering a TypeScript error with my HomePage Class Component. Below is the code snippet: import * as React from "react"; import { Dispatch, AnyAction } from 'redux'; import { connect } from 'react-redux&apos ...

Combine a constant interface with a generic function to create a unique generic interface

When dealing with legacy code that utilizes a const in the following pattern: const fnUsedInSetPrototypeOf = { equalityComparer<T>(a: T, b: T) { return a === b }, otherFn<T> (this: T) { /*...*/ }, // ... other things, all along the ...

Error: Unable to inject HttpClient dependency. Angular 5

I recently switched to using the Angular template in Visual Studio 2017 and decided to update to Angular 5.2. However, I encountered an error while trying to make a http call from the service class. The error message I received is: https://i.sstatic.net/p ...

Angular -How to Create a Text Input Field for Mobile Phones that Only Accepts Numbers

When working with Angular 9, I implemented an input field that only allows numbers using the following code snippet: Html File: <mat-form-field> <mat-label>{{fields.label}}</mat-label> <input pattern="[0-9]*" [formControlN ...

Encountered issue with deploying Angular app to Firebase platform

After attempting to deploy my Angular 4 application on Firebase, I noticed that the setup process did not prompt me for any configuration details as outlined in various resources online. Despite running the 'firebase init' command and only being ...

Utilizing Angular2 to handle HTTP requests and maintain JSON data for responses

Currently I am experimenting with Angular2 along with TypeScript and encountering some challenges while trying to fetch the response from my http request. The response is an array coming from the server and I have a predefined class that is meant to be ass ...

Ensuring File Size and Format Compliance in Angular's HTML and TypeScript

I'm currently tackling a file upload feature on an ASP.net webpage using Angular. I have a question: How can I verify if the uploaded file is either a PDF or JPG and does not exceed 2MB in size? If these conditions are not met, I would like to displa ...

Tips for customizing the default styles of PrimeNG's <p-accordion> tag

Hello, I have encountered an issue with my html code snippet. I am attempting to create a tab with a label-header named "Users", but the accordion tag consistently displays it as underlined. <div class="ui-g"> <p-accordion id="tabsHeader"> ...

Retrieve the output of a function in TypeScript

I'm encountering a challenge with returning a string instead of a function in an object value. Currently, an arrow function is returning an array of objects, and one of them needs to conditionally change a value based on the input value. Here is the ...

Matching TypeScript search field names with column names

Seeking ways to create an API that allows admins to search for users in the database using various fields. // Define allowed search fields type SearchFieldType = 'name' | 'memberNo' | 'email' | 'companyName'; const ...

Enhancing React TypeScript: Accurate typings for Route's location and children attributes

I am facing an issue with my router as it passes props of location and children, but I am uncertain about the correct types for these props. Here is the code snippet for the router using react-router-dom... import React, { useReducer } from 'react&a ...

The Sequence of Import Statements in Angular 2

The Angular Style Guide provides recommendations on Import line spacing: It is suggested to include one empty line between third-party imports and application imports. Consider arranging import lines in alphabetical order based on the module. For destruc ...

Utilizing TypeScript in a browser with a .NetCore WebApplication

After going through numerous articles, I have not been successful in finding a solution. My challenge lies with a .net core WebApplication that utilizes typescript code instead of javascript. Here are the specific requirements: I need to be able to debu ...

Having trouble sending data with a POST request using Angular 4's HttpClient?

Angular 4.4.4 This is an introduction to my app component constructor( private http: HttpClient, ) this.http.post('/api.php', {name, age}).subscribe(response => { console.log(response); }); api.php -> exit(json_encode($_P ...

The error message "Property '$store' is not defined on type 'ComponentPublicInstance' when using Vuex 4 with TypeScript" indicates that the property '$store' is not recognized

I'm currently working on a project that involves using TypeScript and Vue with Vuex. I've encountered an error in VSCode that says: Property '$store' does not exist on type 'ComponentPublicInstance<{}, {}, {}, { errors(): any; } ...

Angular 13 does not currently have support for the experimental syntax 'importMeta' activated

Since upgrading to angular 13, I've encountered an issue while attempting to create a worker in the following manner: new Worker(new URL('../path/to/worker', import.meta.url), {type: 'module'}) This code works as expected with "ng ...

The concept of self-referencing in TypeScript

I recently developed a Vue plugin that allows me to easily access constant objects in the templates of .vue files using shortcuts: <template> <span>{{ $consts.HELLO }}</span> </template> export default { constants: {HELLO: ...