Home > Software engineering >  Angular: Behavior Subject Value is not persisting in service
Angular: Behavior Subject Value is not persisting in service

Time:04-21

i've created 2 components "search-bar" and "search-results" and a shared service "search-results". below is my code: (NOTE): components do not have child and parent relationship. i'm only trying to use behavior Subject to communicate between components and refresh my ui with new results.

"search-results.service":

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class SearchResultsService {

  // Subject to subscribe to
  private results = new BehaviorSubject(null);
  private productsData;

  constructor(private http:HttpClient) { }

  // Http Headers
  httpOptions : Object = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }

  bodyJson = {};
  RESULTS_API_ENDPOINT = "API_END_POINT_URL";
  
  getResults() {
    this.getAPIResults();
    return this.results.asObservable();
  }

  getAPIResults() {
    this.http.post(this.RESULTS_API_ENDPOINT , this.bodyJson, this.httpOptions).subscribe(res => this.results.next(res));
  }

}

"search-results.component.ts"

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { Observable, Subject, throwError } from 'rxjs';
import { SearchResultsService } from '../../services/search-results.service';

@Component({
  selector: 'app-search-results',
  templateUrl: './search-results.component.html',
  styleUrls: ['./search-results.component.css'],
  providers: [SearchResultsService]
})

export class SearchResultsComponent implements OnInit {
  
  public productsData: Object;
  
  constructor(private resultsService: SearchResultsService) {}

  ngOnInit() {
    this.resultsService.getResults().subscribe((res) => (this.productsData = res));
  }

}
<div *ngFor="let product of productsData.products;">
    <h3 >
        <a [href]="product.productDetailPage">
            {{product.name}}>
        </a>
    </h3>
</div>

"search-bar.component.ts"

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { SearchResultsService } from '../../services/search-results.service';

@Component({
  selector: 'app-search-bar',
  templateUrl: './search-bar.component.html',
  styleUrls: ['./search-bar.component.css'],
  providers: [SearchResultsService]
})

export class SearchBarComponent implements OnInit {

  searchForm: FormGroup;
  searchTerm: string;
  newData: Object = {};

  constructor(private resultsService: SearchResultsService) { }

  ngOnInit(): void {
    this.searchForm = new FormGroup({
      searchField: new FormControl()
    });
    this.resultsService.getResults();
  }

  Submit() {
    this.searchTerm = this.searchForm.value.searchField;
    this.resultsService.bodyJson["query"] = this.searchTerm;
    this.resultsService.getResults();
  }

}
<form  [formGroup] ="searchForm" (ngSubmit)="Submit()">
    <label for="searchField">Search Products</label>
    <input formControlName = "searchField" aria-label = "Search Products" id="search_products" class = "vs-input" type="text" name= "searchProducts" placeholder= "Search placeholder"/>
    <span  (click) = "Submit()"></span>
</form>

when i debug in inspector, i see the API data being added to the subject. but, my html is not being updated with products data in search-results component. please advice. this is my first time using Behavior Subject

CodePudding user response:

You are providing providers: [SearchResultsService]

In both components, when it is injected into root.

Remove providers: [SearchResultsService] from both components. Give that a try and let me know if that works.

CodePudding user response:

"search-bar.component.ts" file call the getAPIResults() function instead of getResults()

"search-results.service" file remove this line this.getAPIResults()

  • Related