The Angular Subject() Observable is not functioning properly in another component

manage-employee.component.ts

  @ViewChild(DxDataGridComponent) dataGrid: DxDataGridComponent;
  gridForManageEmployee: any;

  constructor(
    private router: Router,
    private employeeService: EmployeeService
  ) {
    this.loadEmployeeData();
  }

  onEmployeeSelectionChanged(param) { //the event when someone selects an employee
    if (this.dataGrid.selectedRowKeys.length === 1) {
      this.disableFindEmployeeButton = false;
    } else {
      this.disableFindEmployeeButton = true;
    }
    this.selectedEmployee = param.selectedRowsData[0];
    this.employeeService.sendSelectedEmployee(this.selectedEmployee); // send it to service
    console.log(this.dataGrid.selectedRowKeys.length);
   }

employee.service

@Injectable()
export class EmployeeService
{
    selectedEmployeeSubject = new Subject<any>();
    selectedEmployees = [];

    constructor(private http: Http, private platformLocation: PlatformLocation, private apiResolver: ApiResolver) {       
        this._baseUrl = apiResolver.GetHumanResourceUrl(platformLocation);
    }

    sendSelectedEmployee(id: any) {
        this.selectedEmployeeSubject.next(id);
    }

    getSelectedEmployee(): Observable<any> {
        return this.selectedEmployeeSubject.asObservable();
    }
}

menu.component.ts


constructor(public settings: SettingsService, private router: Router, private employeeService: EmployeeService) {
    this.employeeService.getSelectedEmployee().subscribe( //listener in constructor
      (selected: any) =>{
        if(selected != null){
          this.showReportLabel = true;
          this.showSalaryPivotTable = true;
          this.showTransactionsLabel = true;
          this.showRoosterList = true;
        }
        console.log(selected);
      }
    );
}

ngOnInit() {
    this.router.events.subscribe((event: any) => {
      if (event instanceof NavigationStart) {
        this.settings.hideSidebar("left");
      }
    });
    this.employeeService.getSelectedEmployee().subscribe( //listener in ngOninit
      (selected: any) =>{
        if(selected != null){
          this.showReportLabel = true;
          this.showSalaryPivotTable = true;
          this.showTransactionsLabel = true;
          this.showRoosterList = true;
        }
        console.log(selected);
      }
    );
}

menu.component.html

<div class="list-nav-item" routerLinkActive="active" *ngIf="showSalaryPivotTable">
                    <a routerLink="/payroll/employee-for-pivot-table-salary" class="list-nav-link">
                        <span class="list-nav-icon">
                              <i class="fa fa-adjust"></i>
                          </span>
                        <span class="list-nav-label">Pivot Table Salary</span>
                    </a>
                </div>

To achieve the desired behavior, I am attempting to modify the value of the menu property like showSalaryPivotTable to true in menu.component.ts when it listens to the employee selection event onEmployeeSelectionChange() (for displaying the hidden menu).

In order to accomplish this, I am using a Subject() in my service and expecting that after triggering onEmployeeSelectionChange() in the menu.component.ts, it would listen to that event, but it is not working as expected. Am I overlooking something crucial with this Observable concept?

Answer №1

Consider implementing the replay subject without requiring any initialization

import {ReplaySubject } from 'rxjs/Rx';
@Injectable()
export class EmployeeDataService
{
    usersSelected = new ReplaySubject<any>(1);
    selectedItems = [];

    constructor(private http: Http, private platformLocation: PlatformLocation, private apiResolver: ApiResolver) {       
        this._endpoint = apiResolver.GetHumanResourceUrl(platformLocation);
    }

    sendSelection(id: any) {
        this.usersSelected.next(id);
    }

    getSelection(): Observable<any> {
        return this.usersSelected.asObservable();
    }
}

Answer №2

First step is to try changing the way the subject is initialized:

selectedUsersSubject: Subject<any> = new Subject<any>();

If that doesn't work, you can attempt the following method:

find-employee.component.ts change from

this.employeeService.sendSelected(this.selectedEmployee);

to this

this.employeeService.selectedUsersSubject.next(this.selectedEmployee);

Then, wherever you need to access the data, simply subscribe to selectedUsersSubject:

this.employeeService.getSelected().subscribe(
   (data) => this.someData = data // then proceed with other operations
);

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

Unable to retrieve req.body data, despite having body-parser enabled

I've been working on setting up my login functionality, but I'm running into an issue with accessing the req.body object. Initially, the post route wasn't triggering at all (no console.log output in terminal) and the request would eventuall ...

Bringing together variables that are influenced by other variables

I'm attempting to model the flight pattern of a drone using observables for tracking altitude changes. The altitude behavior should follow this specific sequence: Altitude increases from 0 to BaseAltitude, which is a fixed height. Once the drone rea ...

Please indicate the Extended class type in the return of the child Class method using TypeScript 2.4

I'm currently in the process of upgrading from TypeScript version 2.3.2 to 2.4.2. In the previous version (2.3), this piece of code functioned without any issues: class Records { public save(): Records { return this; } } class User extends ...

How to Deactivate Telerik MVC DatePicker through JavaScript

I am facing a challenge with disabling the Telerik MVC DatePicker. The issue arises because the Telerik MVC datepicker is dynamically added to the DOM using the jQuery html() function. Once it is loaded into the DOM, I need to disable it. Unfortunately, I ...

"Element UI, featuring a wide array of components, contributing to bloated bundle sizes

I was looking into the following link. After following the instructions, I realized I am using class based components. Therefore, I am importing as shown below: import {Checkbox} from 'element-ui'; @Component({ components: { Checkbox } }) e ...

Generating a dynamic list of reactive checkboxes in vue.js using data from API call

I'm currently working on a vue.js component that utilizes a search field to query the Google Places API (for simplicity, I've removed some details). The response from the API is a list of checkboxes representing different places. My goal is to se ...

What is the best method for selecting the parent using jQuery?

How can I dynamically add a "selected" class to the parent item if any of its children have a "selected" class in my recursive menu setup shown below? <ul> <li class="administration first"> <a href="/administration.aspx">&l ...

It is not possible to personalize color palettes on Material UI themes while using TypeScript

By customizing the Palette with additional properties, I create a type interface as shown below: declare module @material-ui/core/styles/createMuiTheme { interface PaletteColor { transparency?: string; customGradient?: PaletteColor; } interf ...

Problem concerning the distinction between local and global scope as well as the presence

I have this code snippet for creating a calculator: const numbers = document.querySelector('.numbers') const display = document.querySelector('.display') const functions = document.querySelector('.functions') const equalClear ...

What is the best way to merge the Material UI mini variant drawer with the code used for the dark theme switch

Using the example code from the mui mini variant drawer (https://mui.com/material-ui/react-drawer/) along with a code snippet for a dark/light theme switch, I encountered an issue where the switch does not seem to affect anything: import * as React from &a ...

Update the ng-model in AngularJS when the value is set to true

Hello there, I am in the process of developing an app that provides a summary of data from a database. In this app, there is a form that populates input fields with information using ng-model. Users can edit these values as needed. However, I want to ensu ...

Standardize API response using NgRX Entity

Can the NgRx Entity library normalize a nested JSON api response? If I have data structured like this: [ { "id": "1", "title": "My first post!", "author": { "id": "123", "name": "Paul" }, ...

Initiate a search query only when a minimum of 3 characters have been entered in the respective

In my application, I am utilizing Spring MVC, Hibernate, and JSP. I have successfully implemented a search functionality for multiple fields, triggering it using the onKeyUp() function in JavaScript. However, I now need to modify it to only execute the s ...

Can Promise be used as a tool for implementing asynchronous programming?

I've been delving into the Promise functionality on Google's source code, but have yet to uncover how it handles executing code asynchronously. My current understanding of asynchronous functions is that code following them may be resolved before ...

Another approach to utilize JavaScript for populating content into a <div> container?

Upon loading the page, I aim to display a message in the <div> element. Below is the HTML and JavaScript code I have implemented: <body onload="printMsg()"> <div id="write"></div> </body> function printMsg() { var no ...

Is there a way to verify if a capturing group has been involved in the regex or not?

Looking to extract website URLs from text and have a regex in place so far. ((http|https):\/\/)?(www\.)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*) Issue: If www. is made optional, the re ...

What is the best way to categorize different types of countries in Typescript using optional keys?

I am working on creating a specialized country region map to ensure accurate selection of countries and their respective regions. I want to focus only on the relevant countries and regions, allowing for flexibility in choosing which keys to include while e ...

Troubleshooting a Laravel method invoked in JavaScript using PhpStorm

I'm seeking some advice on how to debug a Laravel function mapped in a JavaScript function that is being called in an HTML page. $('#upload-avatar').fileapi({ url: '{{ route("user.avatar") }}', accept: 'image/*&a ...

How to efficiently utilize the `find` method of `QueryList` within an Angular HTML template

Can methods be utilized on QueryList within the HTML template? For example, in the TypeScript file I can use: @ContentChildren(DonneeEntiteDirective) content!: QueryList<DonneeEntiteDirective> let test = this.content.find(e => e.name === 'su ...

Storing a collection of strings in a mongoose schema: A step-by-step guide

I am working with a user schema that looks like this: const UserSchema = mongoose.Schema({ username: { type: String, required: false }, social: [{ facebook: { type: String, required: false ...