Search code examples
angulartypescriptrxjsngrx

Ngrx get Item from store State: Type 'Item[]' is missing the following properties


I would like to get My store state of Items, but I'm getting an error "not assignable"

ItemReducer

export const initState: Item[] = [...];

export function ItemReducer(state = initState, action: ActionParent) {
  switch (action.type) {
    default:
      return state;
  }
}

ItemListComponent

export class myItemsComponent implements OnInit {

  myItems: Observable<Item[]>;

  constructor(private store: Store<{ items: Item[] }>) {}

  ngOnInit(): void {
    this.store
      .select('items')
      .subscribe((data: Item[]) => (this.myItems = data)); // error here
  }
}

so I have an error like:

Type 'Item[]' is not assignable to type 'Observable<Item[]>'.ts(2322)
Type 'Item[]' is missing the following properties from type 'Observable<Item[]>': _isScalar, source, operator, lift, and 5 more.

Solution

  • myItems is an Observable. Please remove the subscription or change the type of myItems. Removing the subscription (use async pipe) should be the preferred way.

    Remove subscription way

    ngOnInit(): void {
        this.myItems = this.store.select('items');
      }
    

    Change type way

    myItems: Item[];