1

I have a question, I am getting an array as a response from web api

Structure of response is simple:

interface CabinInfo {
    id: number;

    projectId: number;
    cabinId: number;
    ipAddress: string;
    port: number;
}

So now I need to group it by projectId, so naturally i would use rxjs/operators to get some sort od array that i can iterate in html, so I am using:

        this.clientService.GetAllApplications()
            .subscribe(result => {
                const projectsObservable: Observable<CabinInfo> = from(result);
                const projectsList = projectsObservable.pipe(groupBy(cabin => cabin.projectId, cabin => cabin)
                    , mergeMap(group => group.pipe(map(() => ({ projectId: group.key, cabins: group.pipe(toArray())})))));

            }, error => { console.error(error); });

But it does not work as I want, I expect something like

Array<number|CabinInfo[]> 

all I am getting something complex like

Observable<{projectId: number, Observable<CabinInfo>[]}> 

is there a way to convert it to simple array??

2 Answers 2

2

so naturally i would use rxjs/operators

You're living in a strange nature my friend ...

Use the Array.prototype.reduce function :

.subscribe(result => {
  this.groupedResults = result.reduce((p, n) => {
    if (!p[n.projectId]) { p[n.projectId] = []; }
    p[n.projectId].push(n);
    return p;
  }, {});
});
Sign up to request clarification or add additional context in comments.

Comments

1

Since you are using angular you can use async pipe in your html, so you don't need to subscribe your observable but you can let angular handles that logic. Instead, you can operators into your observable.

this.$applications = this.clientService.GetAllApplications()
        .pipe(
            groupBy(cabin => cabin.id),
            mergeMap(group => group.pipe(toArray()))
        );

In your html you'll have something like:

<div *ngFor="let c of $applications | async">

</div>

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.