Struggling to retrieve the most recent emitted value from another component in Angular?

Hello everyone, I am currently attempting to retrieve the most recent updated value of a variable from the component app-confirm-bottom-sheet in the app-bene-verification.ts component, but unfortunately, I am unable to achieve this. Below is the code snippet from the app-confirm-bottom-sheet.ts component:

import { FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ChangeDetectorRef, Component, Inject, OnInit } from '@angular/core';
import { MatBottomSheet, MAT_BOTTOM_SHEET_DATA } from '@angular/material/bottom-sheet';
import { UtilityService } from '../../services/utility.service';

@Component({
  selector: 'app-confirm-bottom-sheet',
  templateUrl: './confirm-bottom-sheet.component.html',
  styleUrls: ['./confirm-bottom-sheet.component.scss']
})
export class ConfirmBottomSheetComponent implements OnInit {

  sheetData: any;
  confirmForm!: FormGroup;
  npciUserName:any=''

  constructor(
    private bottomSheet: MatBottomSheet,
    @Inject(MAT_BOTTOM_SHEET_DATA) public data: any = {},
    private fb: FormBuilder,
    private changeDetector: ChangeDetectorRef,
    private utilityService: UtilityService
  ) {

  }
  ngOnInit(): void {

  }
  updateUserName(): void {
    this.utilityService.updateNpciUserName(this.npciUserName);
  }
  checkNpci() {
    console.log(this.npciUserName);
  }

Below is the HTML from app-confirm-bottom-sheet.html:

      <input type="text" [(ngModel)]="npciUserName" placeholder="Enter your name" (keyup)="updateUserName()" >
   

Now, let's take a look at the code in app-bene-verification.ts:

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators, FormBuilder } from '@angular/forms';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { DatePipe } from '@angular/common';
import { MatBottomSheet } from '@angular/material/bottom-sheet';
import { ConfirmBottomSheetComponent } from './../../../../common/dialogs/confirm-bottom-sheet/confirm-bottom-sheet.component';
import { BankValidationService } from '../../services/bank-validation.service';
import { UtilityService } from './../../../../common/services/utility.service';
import { ExportService } from './../../../../common/services/export.service';
import { Subscription } from 'rxjs';

export interface BeneData {
  agent_ref_id: string
  agent_mobile_no: string
  account_holder_name: string
  
  // Other property declarations removed for brevity

}

@Component({
  selector: 'app-bene-verification',
  templateUrl: './bene-verification.component.html',
  styleUrls: ['./bene-verification.component.scss']
})
export class BeneVerificationComponent implements OnInit {

  npciUserName: any = '';
  npciUserNameSubscription!: Subscription;
  
  // Constructor and other method implementations omitted
  
}

The issue here is that the npciUserName remains set to the default value. The latest value retrieved from app-confirm-bottom-sheet.html is not being reflected in app-bene-verification.ts. To address this problem, we need to modify the code in the utility-service.ts as follows:

import { Injectable } from '@angular/core';
import { MatSnackBar, MatSnackBarConfig } from '@angular/material/snack-bar';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UtilityService {

  constructor(private _snackBar: MatSnackBar) { }
  private npciUserNameSubject = new BehaviorSubject<any>(null);
  npciUserName$ = this.npciUserNameSubject.asObservable();

  updateNpciUserName(value: any) {
    this.npciUserNameSubject.next(value);
  }


So the question remains, how can we access the most recently emitted value of npciUserName from confirm-bottom-sheet in bene-verification.ts?

Answer №1

It's crucial to modify the if statement in the following code block! Currently, the value will only be updated if it matches either '' or null, which is incorrect. The correct approach would be to update the value if it does not equal '' or null!

...
if (this.npciUserName !== '' && this.npciUserName !== null) { // <- revised here!
      this.npciUserName = value;
}
...

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

The validation process in Redux forms

Imagine we have the following types defined: interface MyFormFields { FirstName: string; LastName: string; } type FieldsType = keyof MyFormFields; const field1: FieldsType = "c"; const field2 = "c" as FieldsType; Now, I am looking to implemen ...

TABULAOTR, The complete table calculation is failing to be retrieved

Apologies for any language mistakes, as I am Russian :)I am using Tabulator but facing an issue where the table footer is not being printed. I am also unable to retrieve data from the footer. The footer simply doesn't show up and I'm unsure of wh ...

Identifying the initial object with a duplicate property within an array of objects using JavaScript

In my code, I have an array structured like this: var myArray = [ {id: 1, entry_id: 1, name: 'test', email: 'email1'}, {id: 2, entry_id: 1, name: 'test', email: 'email2'}, {id: 3, entry_id: 2, name: &ap ...

What is the best way to handle mixed parameter types in Spring MVC when sending data from AngularJS?

I am struggling to pass a json object and a string as parameters to my Java controller. Despite my efforts, I keep receiving url = "" in the controller. What could be causing this issue? Is there a solution to successfully passing these parameters? $ ...

Get a calendar that displays only the month and year

I am looking to incorporate two unique PrimeFaces calendars on a single page. The first calendar will display the date, while the second one will only show the month and year. To achieve this, I have implemented the following JavaScript and CSS specifica ...

The issue of Rails 4 serving JavaScript as plain text instead of executing it when attempting to utilize AJAX

I am in the process of constructing a basic page layout featuring two side-by-side columns. The left column is intended for user input via a form submission. Upon submitting the form, I want the right column to dynamically update (using AJAX) and display a ...

Determine whether or not there are any duplicate elements within an array object

Is there a way to determine true or false if there are any duplicates within an object array? arr = [ { nr:10, name: 'aba' }, { nr:11, name: 'cba' }, { nr:10, name: 'aba' } ] arr2 = [ { year:2020, cit ...

Obtain the CSRF token from a webpage using JavaScript

I am currently working on a project where I need to retrieve the csrf token from a web page built with Django using javascript. The structure of my HTML template is as follows: <div class = "debugging"> <p id = "csrf">{% csrf_token %}</p ...

Creating Dynamic Tables with jQuery

I have written a code to fetch values using jQuery and Ajax. The data is coming fine but I am facing an issue with populating the rows in my table. The loop doesn't seem to work properly. Here is my HTML table code: <div class="panel-body"> ...

issues related to implementing search functionality with react-redux

Just starting out with my first react-redux project which is a list of courses, but I have hit a roadblock with redux. I am trying to implement a search functionality based on this answer, and while I can see the action in redux-devtools, it's not ref ...

Ways to modify the values of a Bootstrap Dropdown using a unique identifier

Here is an example of a typical Bootstrap Dropdown: <div class="btn-group"> <button type="button" class="btn btn-lg btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Default option<span class ...

Discover the method to retrieve HTML content by sending an HTTP POST request in AngularJS, similar to loading content

My attempt to retrieve HTML content using Angular Js Post HTTP method was successful, but only for text contents like P tags. I am now trying to fetch HTML contents that include input types such as text boxes using Angular JS. Interestingly, when I utilize ...

Challenges with loading content and async JavaScript within websites

I decided to replace the content on index.htm with the content from project.htm. By clicking on a#front, it redirects to project.htm and dynamically updates the content. However, I am facing an issue regarding how to run the javascript that accompanies thi ...

Encountering a Typescript error while attempting to convert a JavaScript file to Typescript within an Express

After deciding to transition my express.js code to typescript, I have encountered an issue with my user model. Below is a simplified version of the code: //user.model.ts import { Schema, Types } from 'mongoose'; export interface User { na ...

Is it normal for a Firebase listener to trigger twice when adding date to the database in React?

I've developed a basic chat application. Once the user submits a message, it is stored in the database along with their username. this.ref.child("/chat").update({username: this.state.username, message: this.state.chatMessage}); Subsequently, I ...

I have a query regarding the process of filtering data, specifically in the context of

When working with express and mongoose, I often encounter complex queries. As a workaround, I typically retrieve objects by their ID like this: const ticketObj = await Ticket.findById(ticketId); I then use JavaScript's filter method to further narro ...

Dynamically importing TypeScript interfaces for React code splitting

Is it possible to utilize dynamic import('path') for an exported interface? ...

Creating a variety of Flexslider slideshows on the fly

Check out this snippet of code: <?php foreach ($objVideos as $objVideo) : ?> jQuery('#carousel-<?php echo $objVideo->id; ?>').flexslider({ animation: "slide", controlNav: false, animationLoop: false, ...

Tips for addressing lag problems in my Three.js game as time progresses

My game in Three.js doesn't start off with any lag, but after a few minutes, the performance begins to slow down on computers running it. I've tried reviewing my code and checking my arrays, adjusting values to troubleshoot, but so far, nothing s ...

Obtain serialized information from php using ajax

I am currently working with a php script that returns serialized data. I am trying to retrieve this data using the $.ajax() method from jQuery 1.7. You can find an example here. $.ajax({ url: 'http://input.name/get.php?do=lookup' + '&am ...