简体   繁体   中英

rxjs 6 observable<any> to observable<any[]>

I use angular/fire valueChanges() get a document

const countries: Observable<any> = this.AngularFireStorage
      .doc('country/country')
      .valueChanges()

if add pipe(tap(x => console.log(x)). It will log

{ jp: {id: jp}, us: {id: us}}

what I want is add pipe(tap(x => console.log(x)) and get

{id: jp}
{id: us}

How to convert countries: Observable<any> to countries: Observable<any[]>

Instead of pipe(tap(x => console.log(x))

Write:

pipe(tap(x =>
    const result = [];
    Object.keys(x).forEach(key => result.push(x[key]));
    console.log(result);
))

You can use Object.values to turn an object's values into an array. You can use any of the three common higher-order operators ( switchMap , mergeMap , concatMap ) to turn that array into a stream of values.

Here's how that might look:

const countries: Observable<any> = this.AngularFireStorage
  .doc('country/country').valueChanges().pipe(
    concatMap(Object.values),
    tap(console.log)
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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