Within my Angular project, I have implemented a service to share variables across different components. The code for this service is as follows:
import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";
@Injectable()
@Injectable({
providedIn: "root"
})
/**
* Service to manage global variables for use in multiple components
*/
export class SharedService {
// Global variable for the path
private rPathSource = new BehaviorSubject(""); // Set up the source
currentRPath = this.rPathSource.asObservable(); // Make it Observable
constructor() {}
/**
* Function to update the global path from a component
* @param path string representing the path of the R Folder for the ML result
*/
changeRPath(path: any) {
this.rPathSource.next(path);
}
}
In one of my components, I subscribe to the shared variable like so: Component 1
constructor(private shared: SharedService) {}
ngOnInit() {
this.shared.currentRPath.subscribe(RPath => {
this.currentRPath = RPath;
// HERE I MAKE A GET REQUEST
});
}
From another component, I change the variable using: Component 2
this.shared.changeRPath("");
My project includes a sidenav bar with buttons that change the URL and load different components using ng content.
<ng-content></ng-content>
When I click the button to navigate to component 1, the variable is subscribed to and the get request is made as expected. However, when I click the button to navigate to component 2, the shared variable changes and triggers the get request again, even though component 1 is no longer displayed. It seems that component 1 should be destroyed when the component changes, but this is not happening.