Search code examples
rxjsngrx

How can I project one observable array to another with ngrx?


I have a component

export class Test implements OnInit {
  public items: Observable<Item[]>

  constructor(private store: Store<IAppState>)
  
  ngOnInit: void {
    this.items = this.store.pipe(select(selectItems));
  }
}

My item is

export interface Item {
  timestamp: Date
}

I want to transform the timestamp from utc to local. So I want to do something like:

export class Test implements OnInit {
      public items: Observable<Item[]>
    
      constructor(private store: Store<IAppState>)
      
      ngOnInit: void {
        this.items = this.store.pipe(select(selectItems).select(x => new Item { timestamp = new Date(x.timestamp + " UTC") }));
      }
    }

The above syntax is not real (it's based on C# LINQ). I'm trying something along the lines of

export class Test implements OnInit {
      public items: Observable<Item[]>
    
      constructor(private store: Store<IAppState>)
      
      ngOnInit: void {
        this.items = this.store.pipe(map(state => selectItems(state), // something here...));
      }
    }

I'm stuck at the // something here part.


Solution

  • The equivalent of C# LINQ select() is Array.map()

    So assuming your selectItems function returns an array, you can "map" your selected items to Items:

    constructor(private store: Store<IAppState>) {}
    
    public ngOnInit: void {
        this.items = this.store.pipe(map(state => {
            const selectedItems = selectItems(state);
            return selectedItems.map(x => new Item(...));
        }));
    }