10

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]).... Commented Aug 10, 2017 at 16:26

2 Answers 2

17

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()
Sign up to request clarification or add additional context in comments.

5 Comments

the first works, but when using .first() as you mention i get type errors first does not exist on type INTsummary[]
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.
I have a question, how is concatall better then mergeall?
@Maximus In this case it'll do exactly the same thing. I'm not sure about the performance however.
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
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);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.