Functionality for communicating components is only operational on a single platform

I am looking to create a service that can notify my components when there are any changes to the 'idCustomer' property. These changes should trigger certain actions in different components. Currently, I am using console.log to check if the change is received, but it only works for one component. As a newcomer to Angular, I would appreciate suggestions on a more efficient way to communicate the 'idCustomer' property between components. The 'Section' and 'Customer' components are siblings.

LoginService

  idCustomerChanged = new Subject<string>();
  
  constructor(private http: HttpClient) { }

  login(requestBody: any): Observable<ResponseBody> {
    return this.http.post<ResponseBody>(`${this.apiServerUrl}/Customer/GetCustomerLogin`, requestBody);
  }

  addIdCustomer(idCustomer: string) {
    this.idCustomer = idCustomer;
    this.idCustomerChanged.next(this.idCustomer);
  }
  removeIdCustomer() {
    this.idCustomer = '';
    this.idCustomerChanged.next(this.idCustomer);
  }

  getIdCustomer() {
    return this.idCustomer;
  }

LoginComponent (responsible for changing the 'idCustomer')

submit() {
    if (this.form.valid) {
      this.loginService.login(this.form.value).subscribe((response) => {
        if (response.data) {
          this.loginService.addIdCustomer(response.data[0].idCustomer);
          this.router.navigate(['/products']);         
        } else {
          this.error = 'Invalid Credentials';
        }      
      });
    }
}

NavBarComponent (displays the message)

  idCustomer: string = '';
  subscription: Subscription;

  constructor(private loginService: LoginService, private router: Router) {
    this.subscription = this.loginService.idCustomerChanged.subscribe((idCustomer) => {
      this.idCustomer = idCustomer;
      console.log(this.idCustomer + ' from nav-bar');
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

CustomerComponent (does not display the message)

  idCustomer: string = '';
  submenusCustomer = ['Profile', 'History', 'Account Payables'];
  subscription: Subscription;

  constructor(private loginService: LoginService) {
    this.subscription = this.loginService.idCustomerChanged.subscribe((idCustomer) => {
      this.idCustomer = idCustomer;
      console.log(this.idCustomer + ' from customer-page');
    });
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

SectionComponent (also does not display the message)

  idCustomer: string = '';
  subscription: Subscription;

  constructor(private loginService: LoginService) {
    this.subscription = this.loginService.idCustomerChanged.subscribe((idCustomer) => {
      this.idCustomer = idCustomer;
      console.log(this.idCustomer + ' from seccion-page');
    });
  }

  ngOnInit(): void {

  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

Answer №1

It is recommended to include another variable to return the subject as an observable: After setting up your login service and defining your subject, add the following:

  idCustomerChanged = BehaviorSubject<any>({})<string>();
//new
idCustomerChanged$:Observable = idCustomerChanged.asObservable();

//// In your CustomerComponent and other components:

 idCustomerChanged$:Observable;//declare your observable;
    constructor(private loginService: LoginService) {
    this.idCustomerChanged$ = this.loginService.idCustomerChanged$
        this.subscription = this.idCustomerChanged.subscribe((idCustomer) => {
          this.idCustomer = idCustomer;
          console.log(this.idCustomer + ' from seccion-page');
        });
      }

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

When trying to gather multiple parameters using @Param in a NestJS controller, the retrieved values turn out

Can someone help me understand why I am struggling to retrieve parameters using the @Param() decorators in my NestJS controller? These decorators are defined in both the @Controller() decorator argument and the @Get() argument. I am relatively new to Nest ...

Is it possible to modify the parameters of a function by utilizing a MethodDecorator without affecting the "this" value?

Consider a scenario where you need to dynamically modify method arguments using a decorator at runtime. To illustrate this concept, let's simplify it with an example: setting all arguments to "Hello World": export const SillyArguments = (): MethodDec ...

Discovering the IMEI number with Ionic4 and Angular

Recently, I started working with the Ionic framework and I'm trying to find a way to uniquely identify each device. My initial thought was to obtain the IMEI number, but I'm unsure of how to do that. I attempted to use Ionic4 with Angular cordova ...

angular2-seed-advanced encountered an error: RangeError - The maximum call stack size has been exceeded

Attempting to launch the angular-seed-advanced project without modifications on various platforms has been successful for web and desktop (Linux/Windows). However, when trying to run it on Android (emulator and actual device), the following error occurred: ...

Setting a condition for a function call when a checkbox is clicked

My table has columns labeled NoBill and Bill, with checkboxes as the values. Here is the default view of the table: https://i.stack.imgur.com/ZUvb2.png When the checkbox in the NoBill column is clicked, the total value (this.total) is calculated. The t ...

Tips for properly handling a property that receives its value from a callback function and waiting for it to be updated

Below is my TypeScript code: private getInfoSystem = () => { this.systemInfo = { cpuSpeed: 0 , totalRam: os.totalmem(), freeRam: os.freemem(), sysUpTime: os_utils.sysUptime(), loadAvgMinutes: { on ...

When trying to install Angular 6 locally, I encountered an issue with Angular 10 where the package.json file was being ignored

Recently, I encountered an issue with my Angular project. I have a project based on Angular 6.0.7 which I pulled from our repository. On a global level, I have Angular 10.0.4 installed. Despite having the correct version specified in my package.json file, ...

Angular version 8.2 combined with Firebase can result in errors such as those found in the `./src/app/app.module.ngfactory.js` file towards the end of the process when attempting to build with

My first time posing a query on this platform, and certainly not my last. The issue at hand involves the ng-build --prod process failing to complete and throwing errors in my Angular 8.2.14 application. I've integrated Firebase into my project succes ...

What is the process for using infer to determine the return type of a void function?

I am trying to gain a better understanding of how to utilize the infer keyword in TypeScript. Is this an appropriate example demonstrating the correct usage of infer? I simply want to infer the return type of the function below: const [name, setName] = u ...

What is the best way to access an HtmlElement from an Angular component when outside of the

I've been researching extensively, but all the solutions I've found involve retrieving HTMLElement within the component itself or in other components. I am looking to retrieve HTMLElement from an Angular Component within a helper function or so ...

Difficulty Resolving Parameter Resolution in Angular 5 Shared Library Module ([object Object], ?, ?)

I'm facing an issue while attempting to integrate a custom shared component library into my Angular application, which has been upgraded from Angular 5 to Angular 4. Unfortunately, I am unable to resolve the problem at hand. The error message I&apos ...

Change a nested for-loop into an Observable that has been transformed using RxJS

Currently, the following function is operational, but I consider it a temporary solution as I'm extracting .value from a BehaviorSubject instead of maintaining it as an observable. Existing Code Snippet get ActiveBikeFilters(): any { const upd ...

Guide to displaying loading progress during server response delay in React with TypeScript

I need to find a way to update the loading state to false once the server responds. The challenge is that the response occurs in one component, while the progress bar is located in another. To illustrate the scenario: const Form: React.FC = () => { ...

Utilizing union type return values in Typescript

Looking to incorporate shelljs (via DefinitelyTyped) into my Typescript 1.5-beta project. I want to utilize the exec function with the specified signature: export function exec(command: string, options: ExecOptions): ExecOutputReturnValue | child.ChildPro ...

Tips for resolving the issue of loading not appearing on screen in Angular

How can I resolve the problem of the loading animation not appearing? Below is the code snippet: HTML <div *ngIf="tempThermometer | async as temp; else loading"> <ng-container *ngIf="temp.length !== 0; else noItems"> &l ...

Issue with navigating history back in Angular 7 using an iframe

I'm currently working on a single-page application using Angular. I encountered an issue where, when the user presses the browser's back button, only the YouTube iframe content updates and not the entire page. This results in having to press the ...

Is the communication between Angular service and component failing when using ngFor?

I am currently using Angular to create a video game page. When a specific title is clicked, the id is sent to make an API call with that specific id. I am able to retrieve the data in the selected-games component where I intend to use it, but when I use ng ...

Angular Component Test Results in TypeError Error Failure

After defining a custom error class called CustomError: export class CustomError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, CustomError.prototype); } } I want to throw instances of ...

Utilizing Custom Validators in Angular to Enhance Accessibility

I'm struggling to access my service to perform validator checks, but all I'm getting is a console filled with errors. I believe it's just a syntax issue that's tripping me up. Validator: import { DataService } from './services/da ...

The attribute 'disabled' is originally defined as a characteristic within the class 'CanColor & CanDisableRipple & HasTabIndex & MatChipBase'. However, it is replaced in the current context of 'MatChip' as an attribute

After updating my Angular version from 9.1 to 11, I encountered a compilation error. Error: node_modules/@angular/material/chips/chips.d.ts:120:9 - error TS2611:'disabled' is defined as a property in class 'CanColor & CanDisableRipple &a ...