I have a bit of a complicated observable in Angular (courtesy of using Akita, I cannot change this), it's a |
'ed Observable of either an array of Dinosaur
objects, or a single Dinosaur
object, or undefined:
import { QueryEntity } from "@datorama/akita";
export class DinosaurQuery extends QueryEntity<DinosaurState, Dinosaur> {
activeDinosaurs$ = this.selectActive(); // Type: Observable<Dinosaur[]> | Observable<Dinosaur | undefined>
constructor(protected store: DinosaursStore) {
super(store);
}
}
What I want to get from this, as an observable, is either the single object, or the first object in the array in case it is an array. Or undefined, if there is none.
export class DinosaurSelection {
// I want singleSelectedDinosaur$ to be of type: Observable<Dinosaur | undefined>
singleSelectedDinosaur$ = this.dinosaurQuery.activeDinosaurs$.pipe(???);
constructor(protected dinosaurQuery: DinosaurQuery) {}
}
I presume there must be some pipe that does this, but I can't find something appropriate that can act on the |
of an object and an array of that object at the same time. (Or maybe it can't be done with a pipe but in another way, that's also fine.)
just use "pipe(map)" to transform if is array
singleSelectedDinosaur$ = this.dinosaurQuery.activeDinosaurs$.pipe(
map((res:any)=>{
if (res && Array.isArray(res)) //if res and is array
return res[0] //return the first element
return res; //else resut res
}
));