What causes the unexpected behavior of the rxjs share operator when used with an observable in a service?

I attempted to utilize the rxjs share operator in two distinct manners.

  1. Implementing it in the component

Component:

constructor() {
    const obs1 = interval(1000).pipe(
      tap(x => console.log('processing in comp1')),
      map(x => x * x),
      take(1),
      share()
    );

    obs1.subscribe(x=>console.log('testShare1'))
    obs1.subscribe(x=>console.log('testShare2'))
  }

Outcome:

processing in comp1  
testShare1
testShare2

It functioned as anticipated.

  1. Invoking it from an external service.

Service:

export class TestShareService {
  constructor() { }
  testShare() {
    const obs1 = interval(1000).pipe(
      tap(x => console.log('processing in service ')),
      map(x => x * x),
      take(1),
      share()
    );

    return obs1;
  }
}

Component:

constructor(private shareSrv: TestShareService) {
    shareSrv.testShare().subscribe(x=>console.log('testShare1 using service'));
    shareSrv.testShare().subscribe(x=>console.log('testShare2 using service'));

   }

outcome:

processing in service  
testShare1 using service
processing in service  
testShare2 using service

It seems that the rxjs share operator does not have an impact when the observable is situated in an external service. Is this accurate? Or could I be making a mistake?

Appreciate your help.

Answer №1

It is important to assign the observable to a property within the service instead of creating a new one every time a function is called.

export class TestShareService {
  private params$ = new BehaviorSubject<ParamsType | null>(null);
  
  data$ = params$.pipe(
    filter(params => params !== null), // filtering out the initial null
    switchMap(params => this.http.get<YourResponseType>(params)),
    share()
  );

  get(params: ParamsType) {
    this.params$.next(params);
  }

  constructor(private http: HttpClient) {}
}

By doing this, any subscriber to the observable data$ will share the same instance of the observable instead of creating a new one each time. When the get function is called, it triggers the chain to initiate another http call.

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 5 and Bootstrap card with enhanced double-click functionality

I want to design a Bootstrap card that can trigger two of my custom methods. <div (click)="TEST1()" class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Card title</h5> <button (click)="(T ...

Issues with getOptionLabel in Material UI

I have a constant with the following values : const Reference = [ { label: "RF-100", year: "Test" }, { label: "RF-200", year: "Test2" }, { label: "RF-300", year: "Test3" }, ]; and my Autoco ...

ERROR: Unable to call function getTime in Typescript

While working on my function in Typescript, I encountered an issue with two sets of data in the database - date and time, both expecting strings. When users select a date, I trigger a POST request to set the time for them. To handle this scenario, I creat ...

Tips for resolving the error message "TypeError: Converting circular structure to JSON"

I had a straightforward query where I needed to select all from the aliases table. Everything was working fine until I ran npm update. TypeError: Converting circular structure to JSON public async fetchAliases(req: Request, res: Response): Promise< ...

watcher using RxJS

After recently diving into the Observable and Observer pattern, I came across various resources that describe Observable as a producer and Observer as a consumer. However, as I analyzed the code snippet below, I found myself puzzled by the role of the obse ...

Typescript encounters ERROR TS1128: Expecting a declaration or statement

Having trouble with a TypeScript error in my game-details.component.ts file that I've been trying to fix for a couple of hours. It's showing up at line 26, column 54 and everything seems correct to me. Interestingly, when I press CTRL + S in my ...

Searching for similar but not identical results using Knex.js

I am seeking a solution to retrieve similar posts without including the post itself. Here is my approach: export async function getSimilars(slug: string) { const excludeThis = await getBySlug(slug) const posts = await knex('posts') .whe ...

Issue with ESLint error in TypeScript PrimeReact async Button click handler

I am currently facing an issue with exporting data from a DataTable in PrimeReact. The onClick function for the Button does not allow async callbacks as flagged by eslint. Can someone guide me on how to properly call this function? const exportCSV = us ...

Typescript interface designed for objects containing certain optional property names as well as unspecified property names

I am looking to design an interface for an object that can have optional properties with specific names, as well as accept properties with arbitrary names. Here is my approach: interface CallBack { onTransition?(): any; // option A [key: string]: () = ...

What is the reason a type is able to cast to an indexed collection when it is inferred, while an explicit type that seems identical is

I am puzzled by why my inferred types are considered as instances of my more general collection type while my explicit types are not. My goal was to: Have a specific part of my application work with tightly defined collections (e.g., IParents vs IBoss ...

Creating Dynamic ion-card Elements in Typescript by Programmatically Changing Values

Currently, I am working on a basic app that retrieves posts from the server and displays them as cards on the screen. At this early stage, one of my main challenges is figuring out how to dynamically add ion-card elements with changing content and headers ...

Angular ngModel failing to accurately reflect changes in input value

I am facing an issue with implementing a smart number input component that can toggle between allowing or disallowing negative numbers. I have an event listener for the (input) on the <input> element, triggering a function that applies various regex ...

Encountering challenges with Object-Oriented Programming combined with Typescript: Are you experiencing a

Currently, I'm in the process of building a comprehensive authentication application using the MERN stack entirely in TypeScript. However, I am encountering some issues (specifically type errors) with my userController file. Here is my routes file: i ...

Error in Svelte/Typescript: Encounter of an "unexpected token" while declaring a type

Having a Svelte application with TypeScript enabled, I encountered an issue while trying to run it: [!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript) src\api.ts (4:7) 2: 3: export default class API { 4: ...

Errors in TypeScript Compiler for using react-bootstrap in SPFx project

After setting up an SPFX Project with Yeoman generator and including react-bootstrap as a dependency, I encountered errors when using react-bootstrap components and running gulp serve. The error messages are as follows; does anyone have any solutions to ...

Unable to simulate axios instance in a Typescript environment

After reading through this particular article, I decided to attempt writing a unit test while simulating Axios (with Typescript). Incorporating an Axios instance to define the baseUrl. // src/infrastructure/axios-firebase.ts import axios from 'axios ...

Guide on executing .ts script file and building angular 5 with NPM

I am facing an issue with running a file that has a .ts extension before executing npm run build to build my Angular 5 project. package.json "scripts": { "ng": "ng", "start": "ng serve", "compile": "npm-run-all myts build", "myts": "ts-no ...

Combining Several Middleware Functions in NextJs 13 for Authentication and Localization

Important Note If you are interested in exploring my code further, you can find the repository here. To access the specific code for the ott-platform, navigate to apps/ott-platform. Please make sure to create an account on Clerk and input your Clerk key i ...

How can you indicate that a function in TypeScript is expected to throw an error?

An error occurs when trying to compile the following code: "a function whose declared type is neither void nor any must return a value or consist of a single throw statement." Is there a way to indicate to the compiler that _notImplemented throws an excep ...

Steps to retrieve the value stored in a variable within an Angular service from a separate component

How can I effectively share question details and an array of options from one component to another using services? What is the recommended method for storing and retrieving these values from the service? In my question-service class: private static ques ...