Search code examples
angularsignalsangular-signals

Remove undefined results from Angular signals


imagine you have an observable which contains an object of an array
and mapping it to a signal with RxJS interop method toSignal().

data$: Observable<MyData[]> = this.dataService.getData();

dataSignal = toSignal<MyData[]>(this.data$, { initialValue: [] as MyData[]) });

This szenario has some strange conversation error on the initialValue option property.

Is it possible to convert it to a signal of MyData[] which don't have the type signal<MyData[] | undefined>?

Here is a StackBlitz: https://stackblitz.com/edit/angular-fzwsff?file=src%2Fharry-potter-characters%2Fharry-potter-characters.component.html


Solution

  • You can let the inference do its job to match the right function overload Also for this to work you'll have to explicitly

    toSignal(this.data$, {
        initialValue: [] as HarryPotterData[],
      });
    

    or you can also specify the generics :

      data = toSignal<HarryPotterData[], HarryPotterData[]>(this.data$, {
        initialValue: [] as HarryPotterData[],
      });