9

I have a service with a function of type

getSummary(id: string, universe: string): Observable<INTsummary[]>

When I call this I only ever want the first item in the INTsummary[], so I'm trying to use rxjs first operator to do this:

  loadQuickSummary(){
    var obj = this.myService.getSummary(this.user.id, this.user.universe).first();
    console.log("getting quick summary");
    obj.subscribe(r => {
      console.log(`first value ${JSON.stringify(r)}`)
    })
  }

from reading docs and stackoverflow, this should return an object, but instead I get back an array of INTsummary's .

How can I get back just the first object in the INTsummary[] array?

1
  • 1
    Observable.first gives you the first value of the stream of values, not of the array that is one of those values. You need to do that inside a Observable.map, where you have that array -> this.myService.getSummary(...).map(arr => arr[0])....
    – jonrsharpe
    Commented Aug 10, 2017 at 16:26

2 Answers 2

16

The first() return the first emission for an Observable. So when you have source that emits arrays like INTsummary[] then it takes the first array it emits (not the first item in the array).

From your description you want to get the first item in the array so there're are two ways:

this.myService.getSummary(this.user.id, this.user.universe)
  .map(array => array[0])

... or if you really want to use the first() operator:

this.myService.getSummary(this.user.id, this.user.universe)
  .concatAll() // flatten the array into separate emission
  .first()
5
  • the first works, but when using .first() as you mention i get type errors first does not exist on type INTsummary[] Commented Aug 10, 2017 at 16:44
  • You're just not using it right, .first() is a method of Observable and .concatAll() returns an Observable so the problem is somewhere in your code.
    – martin
    Commented Aug 10, 2017 at 16:47
  • I have a question, how is concatall better then mergeall? Commented Aug 10, 2017 at 16:54
  • 1
    @Maximus In this case it'll do exactly the same thing. I'm not sure about the performance however.
    – martin
    Commented Aug 10, 2017 at 16:57
  • 1
    ok, cool, just wanted to understand why you got upvotes and I didnt, I thought maybe you got something better :). And I realize now that the author probably wanted the first item in array, that's how our solutions differ Commented Aug 10, 2017 at 17:06
4

Right, but the object returned is an array, that what this type states:

Observable<INTsummary[]>

If it returned plain objects, you would have:

Observable<INTsummary>

You can use mergeMap operator to flatten the array:

var obj = this.myService.getSummary(this.user.id, this.user.universe).first().mergeMap(r => r);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.