Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This is an example of Rx Observable expand method usage. The idea here is to divide large requests into paged results, then combine the results on the front end. This example will continue to request chunks of data from the backend until it receives a response that says there is no more results to get.
export class ProductService {
constructor(private authHttp: AuthHttp) {}
get(): Observable<any> {
this.products = [];
return this.authHttp.get('/api/products', {search: {limit: 100}})
// Take information from first response and make subsequent responses
// Response body contains: {hasMore: (boolean), nextOffset: (int), data: (array)}
.expand((response) => {
let obj = response.json();
if(obj.hasMore) {
return this.authHttp.get('/api/products', {search: {limit: 100, offset: obj.nextOffset}});
} else {
return Observable.empty();
}
})
// Do any conversions of incoming data required
// Here we are converting string to data with json() then only returning the data portion
.map((res: Response) => {
return res.json().data;
})
// Catch, handle and return observable error or subscriber to handle
.catch((error) => {
return Observable.throw(error._body);
});
}
}
export class ProductsListComponent {
data: Array<any>;
constructor(private productService: ProductService) {
this.getProducts();
}
getProducts(): void {
this.loading = true;
this.data = [];
this.productService.get2().subscribe(
// Handle EACH request's response
(result) => {
result.forEach((product) => {
this.data.push(product);
});
}, (error) => {
console.log('ProductsListComponent.getProducts error', error);
}, () => {
// Complete method gets call once all expanded requests are complete
console.log('ProductsListComponent.getProducts complete');
this.loading = false;
}
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment