Angular 2 shareService: Utilizing the next function with dual subscriptions

I am encountering an issue with my ShareService in angular 2. In another component, I have subscribed to it and the following is my code snippet:

*******ShareService ***********************************
   private ShopItem$ = new Subject<any>();
ShopItem$_ = this.ShopItem$.asObservable();
public addToCart(item : any){

    this.ShopItem$.next(item);

}

*************in another component**********************

_shareService.ShopItem$_.subscribe((item) => {

        alert("hiii"); <====>this functions execute twice
        this.ADD_TO_CART(item);<====>this functions execute twice

 });

I am experiencing a problem where the ADD_TO_CART() function is executed twice! This is causing issues in my cart functionality. How can I resolve this issue? It seems that the ShareService itself is working fine as I have tested it with a different function and it only executes once.

Answer №1

After some discussions in the comments, it seems that the issue could be caused by having multiple subscriptions. To confirm whether this is the case, you can add the following line just before your subscriptions:

console.log('Before subscribing, number of observers: ', _shareService.ShopItem$_.source.observers.length);

Please Note: This code is written for rxjs 4, if you are using version 5, you may need to adjust the syntax.

If the above code prints out a value other than 0, then there is already an active subscription in place.

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

Is it possible to assign a different array to a variable in JavaScript?

I'm facing an issue with manipulating arrays in JavaScript within a function. This problem arises from an exercise found in the book Eloquent JavaScript, focusing on two specific functions: reverseArray(): designed to produce a new array that is the ...

Asp.net isn't cooperating with Jquery Ajax Call

I've tried multiple solutions, but nothing seems to be working. I'm attempting a simple Ajax call using Jquery in Visual Studio 2019, but the code is not hitting the Ajax call. Here's the snippet of my code: <script src="Scripts/jqu ...

Using 'expect', 'toBe', and 'toEqual' in Angular 2 - A step-by-step guide!

Looking to implement something I came across that resembles this: let item1 = {value:5}; let item2 = {value:5}; // Should result in true. expect(item1).toEqual(item2); Unfortunately, an error is being thrown: EXCEPTION: Error in :0:0 caused by: expect ...

Angular Typeahead - bottom bar

I am currently using Angular Typeahead and am looking to add a footer to the search results that directs users to an advanced search page. While I could achieve this with jQuery, I prefer to keep everything within Angular for consistency. <input ty ...

Maintain a fixed element and enable the rest of the elements to scroll as the mobile browser address bar collapses while scrolling upwards

Currently facing a challenge where I want the background image to remain static while the address bar and content underneath scroll up. The image occupies 90% of the view height, and although I've prevented it from resizing and jumping when the addres ...

Using React Native to dynamically change color based on API response

I'm currently working on a React Native project and I have a requirement to dynamically change the background color of a styled component based on the value retrieved from an API. However, I'm facing some challenges in implementing this feature. ...

Angularjs bootstrap nav directive has some bugs that need fixing

My code works fine, but there's a problem: if someone clicks outside the target area (the text label), the directive doesn't fire. Here's my directive: //directive to change active menu class in bootstrap app.directive('activeClass&ap ...

Encountering an Unexpected Token Import Issue with Page Objects in Webdriver.io and Node.js

Hi, I've encountered an issue while attempting to run my test scripts using Node.JS and Webdriver.io. Everything was functioning correctly until I decided to implement the Page Object Pattern. I am now receiving an error in the console output: ERROR: ...

What is the best way to utilize both ng-value and ng-class without any repetition?

I have an input field that utilizes the ng-value attribute along with a filter to showcase a numerical value. <input ng-value="myDataCollection | customFilter"> In addition, I would like to use the ng-class directive to change the color of the text ...

Issue: Unable to locate file 'socket.io-client/dist/socket.io.min.js'

Attempting to set up the Spika backend (node application), I ran into an issue while trying to start the server in standalone mode with the command: $ node src/server/main.js The error that popped up was: Error: Cannot find module 'socket.io-clien ...

What are some ways to incorporate texture into objects using three.js?

Having trouble adding texture to my central sphere (earth) without the object disappearing. Can someone provide guidance on where I might be making a mistake? Your help is appreciated. For reference, here is the link to my jsbin http://jsbin.com/cabape/edi ...

Using jQuery to verify if the content of the tag matches "sometext" before executing a specific action

If I have multiple instances of the following in my content div: <cite class="fn">blabla</cite> What is the best way to check each cite tag's content (e.g. blabla) with a class of fn and change its color to red if it equals "sometext"? I ...

`How can you adjust the language preferences for users in Meteor?`

My website is internationalized using the tap-i18n plugin. I am looking to allow users to switch between languages on the site. Currently, I have a file called client/setLanguage.js where I set the language on startup: getUserLanguage = function () { ...

Utilizing Window function for local variable assignment

Currently, I am facing a challenge in my Angular2 service where I am attempting to integrate the LinkedIN javascript SDK provided by script linkedin. The functionality is working as expected for retrieving data from LinkedIN, however, I am encountering an ...

Incorporating diverse objects in JavaScript through click events

In my Javascript code, I work with two arrays named "array1" and "array2". Initially, the currentArray is set to array1. However, when the user clicks on a certain button, the currentArray switches to array2, and then back to array1 if clicked again. Thi ...

Node.js function failing to return any value

I am facing an issue with retrieving the value of a function as it is not returning anything. Below is the function I am using (Request is an async function that sends a get request): var getVolumesOKCoin = function(pair){ request('https://www.okc ...

Is there a way to retrieve the id of a jQuery autocomplete input while inside the onItemSelect callback function?

I am currently utilizing the jquery autocomplete plugin created by pengoworks. You can find more information about it here: Within the function that is triggered when an entry is selected, I need to determine the identifier of the input element. This is i ...

Tips for effectively combining the map and find functions in Typescript

I am attempting to generate an array of strings with a length greater than zero. let sampleArray2:string[] = ["hello","world","angular","typescript"]; let subArray:string[] = sampleArray2 .map(() => sampleArray2 .find(val => val.length & ...

Using jQuery to extract a specific portion of a URL path

Seeking assistance with extracting category information from lengthy URLs and assigning it to a variable. Consider the following URL: http://example.com/community/home/whatever.html The goal is to assign the variable to the folder path that follows /hom ...

Repeating a PHP variable within an angular scope

When working with PHP, any element prefixed with a $ is recognized as a variable. However, I encountered an issue when attempting to output an Angular statement using the following code: if(...) { echo "return $scope.id;"; } An error message indicated th ...