Hello
Hello

Reputation: 816

How do I set entity in ngrx if it is not an array?

I am learning ngrx/data

From the code sample on line, it uses heros(plural)

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Hero } from '../../core';
import { HeroService } from '../hero.service';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.scss']
 })
export class HeroesComponent implements OnInit {
loading$: Observable<boolean>;
 heroes$: Observable<Hero[]>;

 constructor(private heroService: HeroService) {
   this.heroes$ = heroService.entities$;
   this.loading$ = heroService.loading$;
   }
}

But my application is different, I just use singular object such as hero rather than heroes. I don't have add or delete method. I only want to use update method. The object hero inside may include some list objects. But in the constructor

this.heroes$ = heroService.entities$;

is for an array. How do I change it for a singular object? I mean that I want something like

this.hero$ = heroService.entity$;

Can we do that?

Upvotes: 1

Views: 160

Answers (1)

Pier Daniele Cretara
Pier Daniele Cretara

Reputation: 36

NgRx data can only handles array of entities for its internal architecture, but u can handle your array with single element as well like following script

this.hero: Observable<Hero> = of(initialHero);

this.heroSubscription = heroService.entities$.subscribe((heroes) => this.hero = heroes[0]);

ngOnDestroy(): void {   this.heroSubscription.unsubscribe(); }

You can handle this.hero like an observable of single element of Hero

Upvotes: 0

Related Questions