Skip to content

Instantly share code, notes, and snippets.

@david-fairbanks42
Created April 10, 2018 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save david-fairbanks42/03a59a1cd725e8ffcc4e5bd57e7ae8fb to your computer and use it in GitHub Desktop.
Save david-fairbanks42/03a59a1cd725e8ffcc4e5bd57e7ae8fb to your computer and use it in GitHub Desktop.
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