How can i filter an Observable/BehaviourSubject correctly?

Discussão em 'Angular' iniciado por scxry, Dezembro 15, 2024.

  1. scxry

    scxry Guest

    Service:

    @Injectable({
    providedIn: 'root'
    })
    export class DeckService{
    private decks$ = new BehaviorSubject<Deck[]>([]);

    constructor(private http: HttpClient) {}

    public init(): void {
    this.http.get<Deck[]>('/api/decks').subscribe((decks : Deck[]) => {
    this.decks$.next(decks);
    });
    }

    public getDecks(): Observable<Deck[]> {
    return this.decks$.asObservable();
    }

    public getDeck(deck_id : number) : Observable<Deck> {
    return this.decks$.pipe(
    map(decks => decks.filter(deck => deck.deck_id === deck_id)[0])
    );
    }

    }


    Component:


    public decks$ : Observable<Deck[]>;
    public deckSelected$! : Observable<Deck | undefined>;

    constructor(private deckService : DeckService) {
    this.decks$ = this.deckService.getDecks();
    this.deckService.init();
    }

    ngOnInit() {
    this.deckSelected$ = this.deckService.getDecks().pipe(
    map((decks: Deck[]) => decks.find(deck => deck.deck_id === 58))
    );
    }


    }


    HTML:

    <div *ngIf="deckSelected$ | async as deck">
    <h2>{{deck.deck_id}}</h2>
    </div>


    Deck Model:

    export interface Deck {
    deck_id: number;
    name: string;
    description: string;
    }


    So i want to get a card deck specified by a id. Therefore i want to first fetch all decks in an observable and then filter it. Because using two endpoints ist overkill as i already have them loaded in the app.

    However when running this it just gives me an blank page without any rendered items.

    Continue reading...

Compartilhe esta Página