Having trouble retrieving data from a behavior subject while using switchMap and refreshing in RxJS

app.component.ts

import { Component, OnInit } from '@angular/core';
import { of } from 'rxjs';
import { TestService } from './test.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  posts = [
    { id: 1, name: 'chethan' },
    { id: 2, name: 'rohan' },
    { id: 3, name: 'sai' },
    { id: 4, name: 'yashas' },
  ];

  constructor(private readonly testService: TestService) {}

  getPosts() {
    return of(this.posts);
  }

  ngOnInit(): void {
    this.testService.myData$.subscribe((data) => {
      console.log('from mydata');
      console.log(data);
    });

    // this.testService.mysecondData$.subscribe((data) => {
    //   console.log('from secondata');
    //   console.log(data);
    // });

    this.testService.refresh();
    this.testService.emitProduct(3);
  }
}

test.service.ts

import { Injectable } from '@angular/core';
import {
  BehaviorSubject,
  map,
  Subject,
  switchMap,
  switchMapTo,
  tap,
} from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class TestService {
  private refreshSubject = new Subject<void>();
  refresh$ = this.refreshSubject.asObservable();

  private productSubject = new BehaviorSubject<number>(1);
  product$ = this.refreshSubject.asObservable();

  mysecondData$ = this.product$.pipe(
    tap(() => console.log('coming to mysecondata')),
    map(() => 5)
  );

  myData$ = this.refresh$.pipe(
    tap(() => console.log('myData before switchmap got refresh pipe')),
    switchMap(() => this.mysecondData$),
    tap(() => console.log('myData after switchmap bypassed refresh pipe'))
  );

  emitProduct(data: number) {
    this.productSubject.next(data);
  }

  refresh() {
    this.refreshSubject.next();
  }
}

the observable product$ is not emitting values as expected even when using a behavior subject. This issue occurs despite the use of refresh to switch to product$ which emits 5. The ngoninit subscription does not receive any data even after calling next() on productSubject. Why might this be happening?

Answer №1

By analyzing the code you provided, it appears that the issue may stem from the fact that product$ is based on refreshSubject instead of productSubject.

This means that new values are being emitted into productSubject but they are not connected to anything.

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

Perform a delayed evaluation of the length of the @Input() array

In my Component, I am utilizing an @Input() ids: string[] = []; variable to check if the length equals 1 in the DOM. <mat-expansion-panel *ngFor="let id of ids" [expanded]="ids.length === 1"> ... </mat-expansion-panel> However, when I append ...

When working with Angular, the onSubmit method may sometimes encounter an error stating "get(...).value.split is not a function" specifically when dealing with Form

When the onSubmit method is called in edit, there is an error that says "get(...).value.split is not a function" in Form. // Code for Form's onSubmit() method onSubmitRecipe(f: FormGroup) { // Convert string of ingredients to string[] by ', ...

How to efficiently store and manage a many-to-many relationship in PostgreSQL with TypeORM

I have a products entity defined as follows: @Entity('products') export class productsEntity extends BaseEntity{ @PrimaryGeneratedColumn() id: number; //..columns @ManyToMany( type => Categories, categoryEntity => cat ...

I am struggling to save the value from my input field into the app.component.ts file

Having some trouble storing an input from my form into a property. After submitting, the console.log is showing undefined in the console. I've experimented with different variations, but none seem to be working as intended. <form> <input #i ...

"Introducing the new Next.Js 14 sidebar featuring a sleek hamburger menu

I am in the process of developing a chat application. Currently, I have a sidebar that displays existing conversations and I would like to make it responsive by implementing open and close functionalities for mobile devices. Here is the code snippet for m ...

Tips for resolving the issue of dropdown menus not closing when clicking outside of them

I am currently working on an angular 5 project where the homepage consists of several components. One of the components, navbarComponent, includes a dropdown list feature. I want this dropdown list to automatically close when clicked outside of it. Here i ...

Is there a way to implement retry functionality with a delay in RxJs without resorting to the outdated retryWhen method?

I'd like to implement a retry mechanism for an observable chain with a delay of 2 seconds. While researching, I found some solutions using retryWhen. However, it appears that retryWhen is deprecated and I prefer not to use it. The retry with delay s ...

Mixing a static class factory method with an instance method: a guide

After introducing an instance method addField in the code snippet below, I encountered an issue with the Typescript compiler flagging errors related to the static factory methods withError and withSuccess: The error message states: 'Property ' ...

Position the center of an Angular Material icon in the center

Seeking help to perfectly center an Angular Material icon inside a rectangular shape. Take a look at the image provided for reference. https://i.sstatic.net/oFf7Q.png The current positioning appears centered, but upon closer inspection, it seems slightly ...

TypeScript error message: "The 'new' keyword cannot be used with an expression that does not have a call or construct signature."

Encountered a problem with intersection types in TypeScript... There are three type aliases: Prototype<T> - representing an object or class with a prototype property. DefaultCtor<T> - representing an object or class with a default construct ...

Consolidate multiple generic items into a single entry

In my current project, I am structuring the types for a complex javascript module. One of the requirements is to handle multiple types using generics, as shown in the snippet below: export interface ModelState< FetchListPayload, FetchListR ...

Angular - Modify the Background Color of a Table Row Upon Button Click

I am struggling to change the background color of only the selected row after clicking a button. Currently, my code changes the color of all rows. Here is a similar piece of code I have been working with: HTML <tr *ngFor="let data of (datas$ | asyn ...

Tips for preventing error TS2345 when importing TypeScript components from outside the project directory in Vue

Encountered the following TypeScript error when attempting to use a component outside of the project directory: TS2345: Argument of type '{ template: string; components: { SimpleCheckbox: typeof SimpleCheckbox; }; }' is not assignable to paramet ...

Production environment experiencing issues with Custom Dashboard functionality for AdminJS

I have successfully integrated AdminJS into my Koa nodejs server and it works perfectly in my local environment. My objective is to override the Dashboard component, which I was able to do without any issues when not running in production mode. However, wh ...

The video in the TypeScript code within the Owl Carousel is not displaying properly - only the sound is playing. The video screen remains stationary

I recently updated my query. I am facing an issue while trying to play a video in Owl Carousal with a button click. The video plays sporadically, and most of the time it doesn't work properly. When playing without the carousel, a single video works fi ...

Tips for avoiding sending empty fields when using Angular's HttpClient.post method

Whenever I try to send data using the POST method to my Rest API in Angular, it ends up sending empty fields resulting in my database storing these empty values. I want to find a way to stop this from happening so that no empty fields are sent from Angula ...

bidirectional data binding with programmatically generated input boxes

Is it possible to achieve two-way binding with dynamically created checkboxes? quali=[{class:"10",checked:false},{class:"12",checked:true},{class:"others",checked:true}]; <span *ngFor="let q_list of quali; let i=index" class="lists">  <in ...

Fast screening should enhance the quality of the filter options

Looking to enhance the custom filters for a basic list in react-admin, my current setup includes: const ClientListsFilter = (props: FilterProps): JSX.Element => { return ( <Filter {...props}> <TextInput label="First Name" ...

Enhancing Error Handling in Node.js with TypeScript Typing

Currently, I am working with NodeJs/express and Typescript. When making a request, the compiler automatically understands the type of (req, res), requiring no additional action on my part. UserRouter.post('/user/me/avatar', avatar, async (req, ...

Should the checkbox be marked, set to 1?

I am looking for a way to call a method when the user checks or unchecks multiple checkboxes. Do you have any suggestions on how I can achieve this? Here is what I have tried so far: <input type="checkbox" [ngModel]="checked == 1 ? true : checked == 0 ...