Search code examples
javascripthtmlangularfrontendclient

Function to keep listening a service Angular 8


I have two component, I would one of them keep listening value of a variable set in a service. One component with:

    import { Component, OnInit, Input } from '@angular/core';
    import { SearchService } from '../services/search/search.service';
    
    export class ProductComponent implements OnInit {
    
    @Input() queryValue: string;
    
    ngOnInit() {
    }
    
    onClearFilter() {
      this.resetFilters();
      this._searchService.SetQueryValue(undefined);
      }
    }

And the other one with:

import { Component, OnInit, Input, NgModule } from '@angular/core';
import { SearchService } from '../services/search/search.service';

export class MmSearchComponent implements OnInit {
  queryValue: string;

  constructor(
    private _searchService: SearchService,
    private _configService: ConfigService,
    )
  {
    this.defaultSearch = SearchFilter.ALL;
  }

  ngOnInit() {
  }

  listeningValue() {
   this.queryValue = this._searchService.GetQueryValue();
  }

I would listening Value return undefined, everytime the other service set the variable. Something to listening everytime. Is it possible?


Solution

  • If you are looking for a change of value and an action to be taken based on the change in value, then the best way would be to use Subjects.

    https://www.youtube.com/watch?v=Ft5aDAKuW5Y

    https://blog.angulartraining.com/rxjs-subjects-a-tutorial-4dcce0e9637f