Home > other >  i Need to take one element in result observale
i Need to take one element in result observale

Time:10-20

I want to retun only a valure: in html

 <tr *ngFor="let valCorr of valueCall| async">
        <th>{{valCorr }}</th>
    </tr>

in ts

 valueCall:Observable<number[]>
    //this.studentService.getResult() return an Observable<number[]>
     this.valueCall:Observable=this.studentService.getResult().pipe(map(result=> result.filter(x => x>2)),take(1));

in my serivce

 getResult():Observable<number[]> {
    return of([1,2,3,4,5,6]);
  }

the result is not only one element take it seems doesn't work. anyone can help me?

CodePudding user response:

Hi buddy you do that with this approach use find instead of filter to get single value and then convert that single value to type array

this.valueCall = this.getResult().pipe(
  map((result) => {
    let a = result.find((x) => x > 2);
    return [a];
  })
);

CodePudding user response:

take rxjs operator not get one element else only execute one time the observable and unsubscribe, you're looking for

map((result:any[])=> {
  const values=result.filter(x => x>2)
  //be sure there're at least one element else return null
  return values.length?values[0]:null
})

UPDATE: About "take" If we has an observable like

getResult():Observable<number[]> {
    return timer(0,1000); //return 0,1,2,3.... each second
}

If we use pipe(take(1))

getResult().pipe(take(1)) 

When receive the first value (0) we unsubscribe -no more values are getting-

see a simple stackblitz

  • Related