Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

81
Visualizações
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 Respostas
Responde à pergunta

0

getById(id:number){
  return this.beerSubject.value.find((beer) => beer.id === id);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda