Home > Software design >  How to search for a single object in a BehaviourSubject array
How to search for a single object in a BehaviourSubject array

Time:12-08

RxJS noob here and probably I'm going totally wrong...

I'm trying to get an object by its ID from a BehaviourSubject array.

Here's some code:

service.ts:

import { iBeer } from './../models/beer';
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators'

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

private beers: iBeer[] = beerList;
private beerSubject = new BehaviorSubject<iBeer[]>(this.beers);
beers$ = this.beerSubject.asObservable();


getAll():Observable<iBeer[]>{
  return this.beers$
}

getById(id:number){
  return this.beers$.pipe(
    map(beer => beer.find(beer => beer.id === id)))
  }
}

component.ts:

import { BeerService } from './../beer.service';
import { iBeer } from './../../models/beer';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'shop',
  templateUrl: './shop.component.html',
  styleUrls: ['./shop.component.css']
})
export class ShopComponent implements OnInit {

  beers!: iBeer[];
  beerID?: iBeer;
  id:number = 0;

  constructor(private BeerService:BeerService) { }

  ngOnInit(): void {
  this.BeerService.getAll().subscribe(
    (data:iBeer[]) => this.beers = data);


  this.BeerService.getById(this.id).subscribe(
    (data) => this.beerID = data)
  }

  selectedID(id:number){
    this.BeerService.getById(id).subscribe(
      (data) => this.beerID = data)
  }
}

I get the following problems:

  1. The onInit correctly call and show the object with the default id value. If I try to insert another ID from the html input, it correctly goes to the service method but it always return undefined.

  2. I tried to remove the call inside the onInit. If I do the first call with the default ID, it correctly shows the relative item, but if the default ID is for example 3 and I set 1 from the Html input for the first call, it returns undefined.

How can I resolve this?

CodePudding user response:

getById(id:number){
  return this.beerSubject.value.find((beer) => beer.id === id);
}
  • Related