2
votes

I am requesting an API, that gives me an array back. Now I want to split this array into its components, so that we can make use of e.g. the "take" function of the Observables.

I am using Angular 2 / RxJS.

My current working code is:

public getFiltered(groupName:string, start?:number, num?:number):Observable<AddressGroupInfo> {
    start = start || 0;
    num = num || 0;

    return new Observable((observer) => {
        this.apiClient.post('AddressGroup/GetFiltered', {
            GroupName: groupName,
            StartValue: start,
            ResultCount: num
        }).map((pagedResultOfAddressGroupInfo:PagedResultOfAddressGroupInfo) => {
            return pagedResultOfAddressGroupInfo.ItemList;
        }).subscribe(
            (itemList) => {
                for (let item of itemList) {
                    observer.next(item);
                }
                observer.complete();
            },
            (error) => observer.error(error)
        );
    });
}

Is there a way to get rid of the outter Observable and just use a method on the inner observable to split the array?

thanks & greets

Dominik

1

1 Answers

1
votes

Supposing your API returns a promise which resolves into an array, you could use a simple concatMap. For instance (jsfiddle):

public getFiltered(groupName:string, start?:number, num?:number):Observable<AddressGroupInfo> {
start = start || 0;
num = num || 0;

return Rx.Observable.from(this.apiClient.post('AddressGroup/GetFiltered', {
        GroupName: groupName,
        StartValue: start,
        ResultCount: num
    })).concatMap(x => x)
  });
}