Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

82
Vistas
How to search for a single object in a BehaviourSubject array

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

getById(id:number){
  return this.beerSubject.value.find((beer) => beer.id === id);
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda