The BehaviorSubject will consistently emit identical values to each subscription

I am currently facing an issue with the BehaviorSubject where it emits a value for every subscription. This means that if I have, for example, 2 subscriptions to

this.projectService.projectState$
streams using methods like async or tap, the projectState$ emits twice. Similarly, if I have 3 streams, tap will emit 3 times and so on. I have tried using distinctUntilChanged() and shareReplay(1), but they do not seem to resolve the issue as BehaviorSubject is already hot and does not require shareReplay(1).

project.service.ts:

projectState: BehaviorSubject<any> = new BehaviorSubject(null);
projectState$: Observable<any> = this.projectState.asObservable().pipe(
  distinctUntilChanged(),
  shareReplay(1),
  tap(s => console.log("state", s)) // Outputs state twice
);

projectId$: Observable<string> = this.router.events.pipe(
  startWith(new NavigationEnd(0, "", "")),
  filter(event => event instanceof NavigationEnd),
  map(_ => {
    const { primary } = this.router.parseUrl(this.router.url).root.children;
    const segments = primary && primary.segments;

    return segments && segments[4] && segments[4].toString()
  }),
  filter(id => id && !["admin-areas", "profiles"].includes(id)),
  distinctUntilChanged(),
  shareReplay(1)
);


projectInfo$: Observable<any> = this.projectId$.pipe(
  switchMap(id => this.getProjectInfo(id)),
  shareReplay(1)
)

constructor(private http: HttpClient,
            private appService: AppService,
            private router: Router) {
  this.projectInfo$.subscribe(
    info => this.projectState.next(info)
  )
}

header.component.ts here 2

this.projectService.projectState$
streams subscribed via async

projectName$: Observable<string> = this.projectService.projectState$.pipe(
  filter(info => info),
  map(info => info.name)
);

versionName$: Observable<string> = this.projectService.projectState$.pipe(
  filter(info => info),
  map(info => info.modelVersionsList),
  map(versions => versions.find(v => v.id === this.projectService.getCurrentVersionId())),
  filter(v => v),
  map(v => v.title)
);

header.component.html

<div>{{projectName$ | async}} - {{versionName$ | async} </div>

Answer №1

Experiment with the predefined operator in rxjs known as takeLast(),

For further details, check this link.

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

Issue with Angular 6: Struggling to Implement DatePipe

I am trying to set the current date within a formGroup in a specific format, but I keep encountering an error with the code below: 'Unable to convert "13/07/2020" into a date' for pipe 'DatePipe' this.fb.group({ startdateActivi ...

Dealing with missing image sources in Angular 6 by catching errors and attempting to reset the source

When a user adds a blob to my list, sometimes the newly added image is still uploading when the list is refreshed. In this case, I catch the error and see the function starting at the right time: <img src="https://MyUrl/thumbnails/{{ blob.name }}" widt ...

What is the Correct Way to Send Functions to Custom Directives in Angular 2 Using TypeScript?

I am relatively new to Angular 2. I am currently in the process of upgrading my application from AngularJS and focusing on completing the UI/UX development. There is one final issue that I am seeking help with, and I appreciate any assistance provided. Cu ...

Exploring the implementation of Observable within a Custom Validator in Angular

Currently, I am developing a custom validator to validate whether a username is already in use. Below is the definition of my Custom validator: import { AbstractControl } from '@angular/forms'; import { AccountApi } from '../../api/service ...

Is there a way to use a single url in Angular for all routing purposes

My app's main page is accessed through this url: http://localhost:4200/ Every time the user clicks on a next button, a new screen is loaded with a different url pattern, examples of which are shown below: http://localhost:4200/screen/static/text/1/0 ...

Bovine without Redis to oversee queue operations

Can Bull (used for job management) be implemented without utilizing Redis? Here is a segment of my code: @Injectable() export class MailService { private queue: Bull.Queue; private readonly queueName = 'mail'; constructor() { ...

Angular 5 Component persists despite change in child route

Hello, I'm facing an issue with my Angular 5 App. I have created a simple app with component routing structured as follows: { path: '', component: SetupComponent, pathMatch: 'full' }, // landing page { path: 'setup', com ...

What could be causing this particular issue when using the Firestore get() method? The error message states: "ERROR TypeError: snaps

In my current Angular project, I am utilizing Firebase Firestore database and have implemented the following method to execute a query: findArtistBidsAppliedByCurrentWall(bid):Observable<Bid[]> { console.log("findArtistBidsAppliedByCurrent ...

How to conceal the side navigation bar on specific pages or components within an Angular application

Currently immersed in developing a web application with Jhipster and Angular. I've managed to set up a side navbar along with a top navbar on every page. However, I'm struggling to hide the side navbar on specific pages and could use some guidanc ...

Having trouble installing dependencies in a React project with TypeScript due to conflicts

I encountered a TypeScript conflict issue whenever I tried to install any dependency in my project. Despite attempting various solutions such as updating dependencies, downgrading them, and re-installing by removing node_modules and package-lock.json, the ...

What is the best way to simultaneously utilize two APIs where one is using HTTP and the other is using HTTPS?

What is the best way to simultaneously use two APIs, one being http and the other https, in Angular or JavaScript? ...

How can I generate pure JavaScript, without using Typescript modules?

Take this scenario as an example ... index.ts import { x } from "./other-funcs"; function y() { alert("test"); } x(y); other-funcs.ts import { z } from "some-module"; export function x(callback: () => void): void { z(); callback(); } ...

Using the map operator in an Angular 7 application with rxjs

Despite successfully compiling my code and having everything work perfectly, I encountered an error message in my IDE (Visual Studio Code) that is preventing me from deploying my app using ng build --prod: ERROR in src/app/training/training.service.ts(6 ...

How to convert typescript path aliases into relative paths for NPM deployment?

I am currently working on a typescript project that utilizes paths for imports. For instance: "paths": { "@example/*": ["./src/*"], } This allows the project to import files directly using statements like: import { foo } from "@example/boo/foo"; Whe ...

Solving runtime JavaScript attribute issues by deciphering TypeScript compiler notifications

Here is a code snippet I am currently working with: <div class="authentication-validation-message-container"> <ng-container *ngIf="email.invalid && (email.dirty || email.touched)"> <div class="validation-error-message" *ngIf=" ...

Incorporate any enum value into a Typescript interface

I'm working with a Typescript interface export interface MyInterface { valid: boolean; resourceType: MyEnum; message: string; } As well as an enum enum MyEnum { 'a', 'b', 'c' } Is there a way to allow the ...

Integrate TypeScript into the current project

As a newcomer to Typescript, I am currently exploring the option of integrating it into my current project. In our MVC project, we have a single file that houses the definitions of all model objects. This file is downloaded to the client when the user fir ...

Tips for overlaying text on an image in html with the ability to zoom in/out and adjust resolution

My challenge is aligning text over an image so that they move together when zooming in or out. However, I am facing difficulties as the text and image seem to move in different directions. I have attempted using media queries and adjusting the positions of ...

Navigating through different views in Angular 2 using UI Router and ng2 routing directly from

I am currently utilizing the UI-Router ng2 and attempting to change routes after a certain function is triggered. My code snippet looks like this: SomeFunction() { if(condition){ router.navigate(['/newRouteName']); } } It's ...

Error: The jasmine framework is unable to locate the window object

Currently, I am testing a method that includes locking the orientation of the screen as one of its functionalities. However, when using Jasmine, I encountered an error at the following line: (<any>window).screen.orientation.lock('portrait&apos ...