2
votes

I am attempting to create a service with Angular that returns a particular data set.

The shape of the object returned from the api is this:

{
  status: string,
  totalResults: number,
  results: [array of objects]
}

so on my service, I want to return an observable of the array of results when status is "ok" and totalResults > 0 (meaning I don't want to return an empty array).

my service is looking like this but I'm struggling with the syntax of iif and want to combine it with pluck.

getData(): Observable<result[]> {
 this.http.get<APIResponseObj>(
            this.url
        ).pipe(
            mergeMap(v =>
                iif(
                    () => v.status && v.totalResults,
                    this.results$(v)
                )
            )
        )
}
1

1 Answers

1
votes

Looking at your code, you could set up your request to use the map operator to decide what to return based on your conditions, since map will wrap whatever value you return in a new Observable by default (so, no need to use iif()):

    getData(): Observable<result[]> {
        return this.http.get<APIResponseObj>(this.url).pipe(
            map((v) => {
                if (v.status && v.totalResults) {
                    return v.results;
                } else {
                    return []; // Although you're stating to not want to return an empty array, in my opinion, an empty array would fit your case, since you're planning to return Observable<result[]>
                }
            })
        );
    }

The method above should return the Observable you're hoping to store in this.results$

this.results$ = this.getData(); // Returns Observable<result[]>

After that, you could, for example, use the async pipe on the view to both subscribe and get the values (the ngFor loop won't attempt to display anything if the array is empty):

<div *ngFor="let res of (results$ | async)">
  {{res}}
</div>

I hope that helps!