How is it that the callback method in the subscribe function of the root component gets triggered every time I navigate between different pages within the application?

I am currently using Angular 10 and have developed a server that returns an observable:

export class CountrySelectionService {

 private _activeCountry = new BehaviorSubject(this.getCountries()[0]);

   public getActiveCountryPush(): Observable<CountrySpec> {
    return this._activeCountry.asObservable();
    }
    
  constructor(private utilService:UtilService){}

  getCountries(): CountrySpec[] {
    return  [new CountrySpec("assets/images/canadaFlag.svg", Country.CA, "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84f7e5e8e1f7c4e0f3edeae2ebaae7ebe9">[email protected]</a>"), 
             new CountrySpec("assets/images/usaFlag.svg", Country.US, "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2251434e47516246554b4c444d0c414d4f">[email protected]</a>")]
  }

  setActiveCountry(countrySpec: CountrySpec): void {
    this._activeCountry.next(countrySpec);
  } 
}

Within the app.component.ts(root component) file, in the ngOnInit function, I call the above method:

ngOnInit(): void {

  this.countrySelectionService.getActiveCountryPush().subscribe({
    x=> { someFoo(x.name) }
  });
}

I was expecting the someFoo callback method to only be triggered when the _activeCountry property is updated. However, it seems that the someFoo callback method is being called not only when _activeCountry is updated but also when navigating to another page within the app.

Any suggestions on why the someFoo method is being triggered even when _activeCountry is not updated? And how can I resolve this issue?

Answer №1

Ensuring that the callback only triggers within a specific component involves adding an ngOnDestroy event to unsubscribe when the component is destroyed.

subscriptionList: Subscription[];

ngOnInit(): void {

  let subscription = this.countrySelectionService.getActiveCountryPush().subscribe({
    x=> { performAction(x.name) }
  });
  this.subscriptionList.push(subscription);
}

ngOnDestroy() {    
    this.subscriptionList.forEach((subscription) => {
      subscription.unsubscribe();
    });
  } 

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

What is the best method for incorporating a delay within the upcoming subscribe block in Angular?

When subscribing to a service method, I have a sequence of actions that need to occur: displaying a toaster, resetting a form, and navigating to another component. However, I want to introduce a delay before the navigation so users can see the toaster mess ...

What steps can I take to ensure that Visual Studio replaces my JavaScript file during the TypeScript build process?

In my development process using Visual Studio to work on my TypeScript project, I have encountered an issue with the build process. I have a build.ts file that links to all of my other TS files and compiles them into one app.js file along with an associate ...

Using System.import in my code is triggering a cascade of errors in my console

I incorporate the System module in my component. export class LoginComponent { constructor() { System.import('app/login/login.js'); } } The file loads successfully, however, TypeScript compiler raises an error Error:(10, 9) TS2 ...

An issue has occurred when attempting to import ES Module for setting all values to an object

Working on a project in Angular 6, I encountered an issue with using the npm package object-set-all-values-to version 3.9.45. Here's what I did: 1- Successfully installed it using npm i object-set-all-values-to ✔️ OK 2- However, when trying to i ...

Creating a generic array type in TypeScript that includes objects with every key of a specified interface

I am working with an interface called Item interface Item { location: string; description: string; } Additionally, I have a generic Field interface interface Field<T extends object> { name: keyof T; label: string; } I want to create an Arra ...

What methods can I use to create an RXJS stream that only updates the state once all sequential calls have been successful?

Currently, I am delving into rxjs within the realm of Angular. However, I am facing difficulties in merging these concepts to accurately portray the following scenario: I initiate an HTTP request to an endpoint, which returns some data This data is then u ...

Tips for integrating Typescript definitions into the Express req and res objects

I have been encountering numerous errors in my REST API controller functions, specifically: error TS7006: Parameter 'req' implicitly has an 'any' type. The same issue is present for res. I have tried various solutions involving typing ...

What is the relationship between directives, templates, and ViewContainers in Angular?

I have implemented a basic functionality in my component where numbers are injected after a delay using a custom directive called *appDelay It is known that the Angular syntax hints with * will de-sugar into something like this: <ng-template ...> .. ...

Is it possible to define a unique function signature in a child class when implementing a method from a parent class?

In the process of developing a repository module that includes generic methods, I have found that as long as each derived class has the `tableName` configured, the basic query for creating, finding, or deleting records remains consistent across all child c ...

Angular 9 is currently activating multiple routes simultaneously

I'm currently working on a user login feature that redirects users to the dashboard upon successful authentication. Although the entire process seems to be functioning correctly, I am facing an issue where both the login form component and the dashbo ...

Error encountered in Snap SVG combined with Typescript and Webpack: "Encountered the error 'Cannot read property 'on' of undefined'"

I am currently working on an Angular 4 app that utilizes Snap SVG, but I keep encountering the frustrating webpack issue "Cannot read property 'on' of undefined". One solution I found is to use snapsvg-cjs, however, this means losing out on the ...

How can you connect one data field to another within Angular?

Angular offers a convenient method for binding the value of an HTML element to a data field. For example, you can achieve this with the following code: <input name="firstName" [(ngModel)]="firstName"/> This means that any text en ...

The type 'MenuOptions[]' cannot be assigned to type 'empty[]'

Even after numerous attempts, I am still grappling with TypeScript problems. Currently, I am at a loss on how to resolve this particular issue, despite all the research I have conducted. The code snippet below is what I am working with, but I am struggling ...

No members were exported by the module, please export an interface

I encountered this error: "/Users/robot/code/slg-fe/src/app/leaderboards/leaderboards.component.ts (2,10): Module '"/Users/robot/code/slg-fe/src/app/leaderboards/leaderboard"' has no exported member 'Leaderboard'. This is what my le ...

Heroku deployment of Angular application encounters launching issue

Currently, I am facing a challenge with deploying my Angular App to Heroku using Git. The application works perfectly fine when run locally through the Angular CLI at localhost. To serve the static files, I have included a small Node.js server. Despite He ...

What is the best way to implement an onClick event listener in a TypeScript React application?

Is there a way to properly add an onClick event listener to a div element in my code snippet below? useEffect(() => { if (ref.current === null) { return; } const handleClick = (el: HTMLDivElement, e: MouseEvent) = ...

Unlocking the power of module augmentation in Typescript: Enhancing library models within your app domain

I currently work with two applications that share the same code base for their models. I am interested in developing and sharing a library model using inheritance in TypeScript. For instance, Pet extends Author. In my current Angular application, I need ...

In order to showcase the data from the second JSON by using the unique identifier

SCENARIO: I currently have two JSON files named contacts and workers: contacts [ { "name": "Jhon Doe", "gender": "Male", "workers": [ "e39f9302-77b3-4c52-a858-adb67651ce86", "38688c41-8fda-41d7-b0f5-c37dce3f5374" ] }, { "name": "Peter ...

Tips for stopping webpack from creating compiled files in the source directory

I'm in the process of transitioning my AngularJs project from ES6 to TypeScript and I've integrated webpack with ts-loader. However, I've encountered an issue where the compiled files and source maps are saved in my directory instead of bei ...

Iterating through a JSON object to verify the presence of a specific value

I have a JSON Object and I am looking for a way in Angular 6 to search for the value "Tennis" in the key "name". Can you provide guidance on how to achieve this? { "id":2, "name":"Sports", "url":"/sports" "children":[ { "id":1, ...