简体   繁体   English

Angular2:获取从数组`|` 中选择单个对象的管道

[英]Angular2: get a pipe that selects from an array `|` a single object

I have a bit of a complicated observable in Angular (courtesy of using Akita, I cannot change this), it's a |我在 Angular 中有一些复杂的 observable(感谢使用 Akita,我无法改变它),它是一个| 'ed Observable of either an array of Dinosaur objects, or a single Dinosaur object, or undefined: 'ed Observable 要么是一组Dinosaur对象,要么是单个Dinosaur对象,或未定义:

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
    }
));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM