Angular 4: Implementing Subscription with Behavior Subject

I am currently working with Angular 4 and utilizing observables.

I have a requirement to share data between components as I am using BehaviorSubject along with observables.

Below is the code snippet:

import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Http, Response } from '@angular/http';

public _searchResultOne = new Subject<any>();
searchResultOne$ = this._searchResultOne.asObservable();


constructor(private http: Http) {}

newsearch() {
    return Observable.forkJoin(
        this.http.get(API),
        this.http.get(API)
    )
        .subscribe(latestValues => {
            const [data_changes, data_all] = latestValues;
            this._searchResultOne.next(latestValues);
        })
}

getNewSearchResults(): Observable < any > {
    return this.searchResultOne$;
}

I am displaying data using load more functionality. Result is fetched using getNewSearchResults() function.

Here is my component code:

import { SearchService } from '../../shared/services/search.service';
import { ISubscription } from 'rxjs/Subscription';

results;

constructor(
    public searchService: SearchService) {

}
ngOnInit() {
    this.searchOne();
}
searchOne() {
    this.subscription = this.searchService
        .getNewSearchResults()
        .subscribe(res => {
            console.log("result", res);
            var freelisting = res[1].response.docs;
            this.results = this.results.concat(this.freelisitingArray);
        }
}

I noticed that the response is being logged multiple times. What could be causing this issue?

The result is subscribed multiple times resulting in duplicate results. Is there a way to prevent multiple subscriptions?

I attempted to use this.subscription.unsubscribe() in ngOnDestroy but still facing duplicate results. Any suggestions on how to resolve these issues?

Your advice would be greatly appreciated.

Thank you.

Answer №1

If you're attempting to create a singleton service to be shared among multiple components, review your module code where you have specified provider: [SearchService]. Make sure to eliminate this provider from the components and only include it in the app.module.ts. By doing this, you will ensure that there is only one instance of the service, maintaining consistency across all components.

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

Creative ways to use images as borders with CSS in React JS

import React, { Component } from 'react'; class BigText extends Component { constructor(props) { super(props); this.state = { title: '', text: '', summary: '' ...

Unable to Display Embed Request Using Javascript in IE9 and IE10

My website allows users to embed content they create on the site into their own blogs or pages using a series of embeds. Here is the code we provide them: <script src="[EMBED PROXY URL]" type="text/javascript"></script> When this code calls ...

What methods can be utilized to efficiently determine if one N-ary tree is a subtree of another, besides simply comparing their pre-order strings?

When faced with a problem of determining if one binary tree is a subtree of another, the usual method involves generating strings by performing pre-order traversals on both trees and then using indexOf to check for the presence of one string in the other. ...

What is the best way to iterate through an array of arrays using a foreach loop to calculate the total number of specific properties?

For instance, if YieldCalcValues were to look something like this: [ [ 850, 500 ], [ 3, 6 ], [ 1200, 5000 ], [ 526170, 526170 ] ] I am looking to create a foreach loop that calculates the yield per for each product. How can I accomplish this correctly? l ...

Issues with the creation of an AngularJS table are causing functionality to malfunction

2021 UPDATE: Note: This question was drafted when I was still learning HTML and JS. If you are seeking assistance for an issue, this might not be very useful as my code was messy. Sorry for any inconvenience caused. The question will remain posted in acco ...

The hyperlink appears to be malfunctioning with an additional border surrounding it within a pop-up window

I am facing an issue with a link <a> not functioning properly with a popup dialog on . Additionally, there seems to be a border that appears around the <a> when the popup initially displays. If you click on "Leer más" for any product, you can ...

When we modify the prototype of the parent object, where does the __proto__ point to?

Typically, when a new object is created using the "new" keyword, the __proto__ property of the newly created object points to the prototype property of the parent class. This can be verified with the following code: function myfunc(){}; myfunc.prototype.n ...

React-router: Issue with ProtectedRoute authentication mechanism not functioning as expected

I'm currently working on setting up protected routes that can only be accessed after the user has logged in. There are two main routes to consider: /login, which is the Login component (public), and /, which is the Dashboard component (protected). Wh ...

The statusMessage variable is not defined within the "res" object in a Node Express application

I am currently developing a Node.js & Express.js application and I am in need of creating a route to display the app's status. router.get('/status', function(req, res) { res.send("Current status: " + res.statusCode + " : " + res.stat ...

Angular provides a variety of functionality to control the behavior of elements in your application, including the

I have a page with Play, Pause, Resume, and Stop icons. When I click on the Play icon, the Pause and Stop icons are displayed. Similarly, I would like to show the Resume and Stop icons when I click on the Pause icon. I need help with this code. Thank you. ...

Unable to change placeholder in Material UI's Select Form

I'm having trouble modifying my SelectionForm. I need to update the color of the placeHolder image from red to a different color, but I can't find any properties or props on the material ui Docs to do so. Can someone assist me with this? https:/ ...

Mastering the Art of Scrolling

Can someone please tell me the name of this specific scrolling technique? I am interested in using something similar for my project. Check out this example site ...

Parsing JSON data on the client side in an ASP.NET application

I am currently working with JSON data that looks like this: "Table":[ { "AF":2000.00 "RegionNumber":1 "RegionName":"Black Sea" }, { "AF":100.00 "RegionNumber":1 "RegionName":"Black Sea" }, { "AF":15000.00 "RegionNumber":2 "RegionName":"Ista ...

Tips for utilizing the 'crypto' module within Angular2?

After running the command for module installation: npm install --save crypto I attempted to import it into my component like this: import { createHmac } from "crypto"; However, I encountered the following error: ERROR in -------------- (4,28): Canno ...

Hide bootstrap card on smaller screens such as sm and md

Utilizing the Bootstrap 4.1 card component, I showcase categories within the right sidebar - check out a sample image of the card here: Card example image; When viewing on smaller screens, it's preferable to collapse this large card as shown in this ...

I'm encountering an error in my routes index.js file that says "Module not found"

The issue is stating "Cannot find module './routes/index'" despite it being located in that directory (even when static is set to that folder) Here is the error: root@ip*censored*:/home/ubuntu/*censored*# module.js:471 throw err; ^ Err ...

The Vuetify Jest button trigger fails to function properly despite utilizing a spy

Recently delved into the world of Vue.js and Jest to see how they interact. I watched some tutorials and then decided to give it a go myself, but ran into trouble with getting the trigger click to work. Within my component, I have a login button, which is ...

Exploring creative methods for incorporating images in checkboxes with CSS or potentially JavaScript

Although it may seem like a basic question, I have never encountered this particular task before. My designer is requesting something similar to this design for checkboxes (positioned on the left side with grey for checked boxes and white for unchecked). ...

Enhance the speed of my Tumblr page by using JavaScript for personalized styling tweaks

-- Hey there! Dear Reader, if navigating Tumblr isn't your cup of tea, let me know and I'll provide more detailed instructions! I recently ran into some glitches on my Tumblr page while using the default theme 'Optica'. Whenever I tri ...

What is the process for transmitting data using an Ajax Query to a Controller and subsequently displaying a new JSP page returned by the Controller?

One issue I am facing involves sending data to a Spring Boot Controller through an AJAX Query and then loading a new JSP page. When I send data to the url in the AJAX Query, which matches the URL in my controller class, it executes the code within that met ...