Search code examples
angularrxjsobservable

My state looks like it's not an Observable


I am trying to implement a store without NgRx and I have made a function in my store.ts that can select every Object I want, like in NgRx:

export interface State {
  user: User | undefined;
  meals: Meal | undefined;
  [key: string]: any;
}

const state: State = {
  user: undefined,
  meals: undefined,
};

select<T>(name: string): Observable<T> {
  return this.store.pipe(
    distinctUntilChanged(),
    map((state) => state[name])
  );
}

In my component I try to select my meal:

export class MealsComponent implements OnInit, OnDestroy {
  meals$ = Observable<Meal[]>;
  subscription!: Subscription;

  constructor(private mealService: MealService, private store: Store) {}

  ngOnInit(): void {
    this.subscription = this.mealService.meal$.subscribe();
    this.meals$ = this.store.select<Meal[]>('meals');
  }

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

Unfortunately it doesn't work. Here is my error message :

Type 'Observable<Meal[]>' is missing the following properties from type '{ new (subscribe?: ((this: Observable<Meal[]>, subscriber: Subscriber<Meal[]>) => TeardownLogic) | undefined): Observable<Meal[]>; prototype: Observable<...>; create: (...args: any[]) => any; }': prototype, createts(2739)

To summarize: I have tried to select an Observable, it don't work and I don't understand the error message.

I don't know if I am intelligible in my question, if not let me know. I really appreciate all the answers I can get.


Solution

  • I have find a way to make all that working :

    select(name: string): Observable<any[]> {
        return this.store.pipe(map((value) => value[name as keyof State]));
      }
    

    That was not easy to find but it actually work...

    Thnak you for all your answer