How Angular services transmit information to components

I have implemented a search field within my top-bar component and I am facing an issue in passing the input value of that search field to another component.

Design

  1. Search service
  2. Top bar component
  3. Result component

Operation

  1. Top bar component receives the input value and forwards it to the Search service
  2. Result component retrieves the input value from the Search service for further processing

Current Status

  1. Successfully obtaining the input value in Top bar component
  2. Unable to retrieve any value in Result component

Code Snippets

TopBar component

// HTML
<input nz-input nzBorderless placeholder="Search here..." (keydown.enter)="onInput($event)" style="background-color: #F3F6FC;" />

// SCRIPT

import { SearchServiceService } from 'src/app/services/search/search-service.service';
@Input() searchName: string;
constructor(
    private globalSearchService: SearchServiceService,
) {}

public onInput(event: any){
    // this pushes the input value into the service's Observable.
    this.globalSearchService.searchTerm.next(event.target.value);
}

Search service

export class SearchServiceService {
  public searchTerm: BehaviorSubject<string> = new BehaviorSubject<string>(null);
  constructor() { }
}

Result component

import { SearchServiceService } from 'src/app/services/search/search-service.service';

public searchTerm: string = "";

constructor(
  private globalSearchService: SearchServiceService
) { }

ngOnInit(): void {
  // this listens to the input value from the service and does something on change.
  this.globalSearchService.searchTerm.subscribe((newValue: string) => {
    console.log('search newValue :', newValue); // Nothing prints here!
    // this is where you would apply your existing filtering.
    this.searchTerm = newValue;
  });
}

Any suggestions?

Update

Q: How did I register my search service?

A:

import { SearchServiceService } from 'src/app/services/search/search-service.service';

const MODULES = [CommonModule, RouterModule, AntdModule, TranslateModule, InfiniteScrollModule, FormsModule, ReactiveFormsModule]

@NgModule({
  imports: [...MODULES],
  declarations: [ACLComponent],
  exports: [...MODULES],
  providers: [SearchServiceService],
})
export class SharedModule {}

Answer №1

Your implementation of the BehaviourSubject in this context is incorrect. To correct it, ensure that you follow this approach. Additionally, avoid exposing all variables as public and eliminate unnecessary constructors.

export class SearchServiceService {
  searchTerm: BehaviorSubject<string> = new BehaviorSubject<string>(null);
  $searchTerm = this.searchTerm.asObservable();
}

When working within your Result Component, remember to subscribe to the Observable instead of directly to the BehaviourSubject.

import { SearchServiceService } from 'src/app/services/search/search-service.service';

searchTerm: string = "";

constructor(
  private globalSearchService: SearchServiceService
) { }

ngOnInit(): void {
  this.globalSearchService.$searchTerm.subscribe((newValue: string) => {
    this.searchTerm = newValue;
  });
}

Answer №2

Issue Resolved

By relocating my service provider from the shared module to the main app module and then rebuilding and serving the application, I was able to resolve the problem.

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

Scraping the web with cheerio: Should we delete or disregard a child element?

There's a specific website I'm looking to scrape, and its structure is as follows: <p><strong>a certain heading:</strong> some information etc. blabla </p> <p><strong>another heading:</strong> more deta ...

Was anticipating 1 argument, however received 5 in TypeScript

When running the code in this part, I expected to receive 0-1 arguments but ended up getting 5 instead. Do you have any suggestions for a solution? Register() { let newUser = new User(this.registerForm.value, newUser.city =this.cityid, ...

Efficiently handling multiple form submissions using a single jQuery Ajax request

I'm working on a page that has 3-4 forms within divs, and I want to submit them all with just one script. Additionally, I want to refresh the content of the specific div where the form is located. However, I'm unsure of how to specify the current ...

The paths specified in Node.js and Express are having difficulty finding the resource files for CSS and JavaScript

I am currently using Express to develop a basic website. Everything was running smoothly until I attempted to add the following code to handle 404 errors: app.get('/*', function(req, res) { res.render('404.ejs',{ title: ' ...

"Exploring the power of Nextjs Server-Side Generation with 10 million

I am working on a Next.js application that utilizes an API to fetch 10 million posts. I am considering using the SSG method for this purpose, but I am unsure if it is the standard approach. Additionally, I may need to add new posts dynamically in the fut ...

Display information from a Google Sheet onto a leaflet map based on specified categories

I am currently facing some challenges while creating a map with markers using data from Google Sheet and leaflet. Despite my efforts, I have encountered a few bugs that are proving to be difficult to resolve: Group Filtering - Although I can successfully ...

Utilize React Native to continuously fetch and display data from this API

[React-Native] Seeking assistance on looping through JSON API for conditional rendering. As a beginner, I would greatly appreciate your guidance. Thank you. Find my code here: https://drive.google.com/file/d/0B3x6OW2-ZXs6SGgxWmtFTFRHV00/view Check out th ...

What is the most efficient way to refresh a React component when a global variable is updated?

I've built a React component called GameData that displays details of a soccer game when it is clicked on in a table. The information in the table is updated by another component, which changes a global variable that GameData relies on to show data. S ...

What is the process for removing a particular file from my bundle?

I am currently utilizing webpack to build my angular2/typescript application and have successfully generated two files, one for my code and another for vendors. However, I am in need of a third file to separate my config (specifically for API_ENDPOINT) whi ...

What is the best approach to implementing a filter in Vue 2 that is also compatible with Vue 3?

Currently, I am utilizing Vue.js 2+ version and have implemented a date formatting filter to meet my needs. However, I recently found out that Vue 3 has removed the filter functionality in favor of using computed properties or methods. My dilemma now is ho ...

Issue with Symbol Constructor in Typescript: [ts] The 'new' keyword can only be used with a void function

Just starting out with typescript and experimenting with the ES6 Symbol constructor. How can I address this ts lint problem without resorting to using any? const symbol = new Symbol(path); I'm trying to avoid doing this: const symbo ...

Express app issues error: JSON response not returned properly - Uncaught SyntaxError: Unexpected end of data

I'm in need of some fresh perspective. My goal is to have a basic Express app return JSON data (in this case, a Firebase token) every time a request is made to it. Here's the code for my Express server: app.get('/validate', function ...

Organize a Javascript array by grouping it based on a specific field and

I have an array that I need to group by the createdAt value. [ { "createdAt": "2021-05-17T14:55:29.836Z", "machine": { "label": "MAQ_100", }, }, { "createdAt": "2021-03-10T13:22:45.694Z", "machine": { ...

What occurs when there are conflicting export names in Meteor?

After researching, I discovered that in Meteor, If your app utilizes the email package (and only if it uses the email package!) then your app can access Email and you can invoke Email.send. While most packages typically have just one export, there a ...

Utilizing ngrx/store in Angular 2 for Search Functionality

In the process of enhancing an angular 4 application, I am working on integrating a search functionality for a data-filled table. The application also utilizes ngrx store to manage state. I am looking for advice on the most effective approach to implemen ...

Bring in styles from the API within Angular

My goal is to retrieve styles from an API and dynamically render components based on those styles. import { Component } from '@angular/core'; import { StyleService } from "./style.service"; import { Style } from "./models/style"; @Component({ ...

Tips for inserting a page break after every item in a loop in Visualforce when generating a PDF document

I need help with rendering a VF page as PDF. The VF page iterates over a list of account records using the repeat tag. I want to apply a page break for each element in the repeat tag. The code below is working, but it has an issue - it shows an empty PDF p ...

Emphasize a modified attribute in *ngFor

I am currently working on a feature that highlights a value whenever it changes within an *ngFor loop to alert the user. I have made some progress in achieving this goal. https://stackblitz.com/edit/ngfor-zhywqy The ngFor directive is being used to displ ...

Incorporating an external JSX file into an HTML page in a React project

I have a React code in my js/script.js file. My HTML page's head tag is structured like this: <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="06746367657246373328302834" ...

Issue with custom leaflet divIcon not maintaining fixed marker position during zoom levels

After creating a custom marker for leaflet maps, I noticed that it shifts position drastically when zooming in and out of the map. Despite trying to adjust anchor points and positions, the issue persists. I have provided the code below in hopes that someon ...