Angular 2 Http, Observables e solicitações recursivas
Eu tenho um ponto de extremidade REST que retorna uma lista de itens, no máximo 1000 itens por vez. Se houver mais de 1000 itens, a resposta terá o status HTTP 206 e haverá umaNext-Range
cabeçalho que posso usar na minha próxima solicitação para obter mais itens.
Eu estou trabalhando emum aplicativo Angular 2 e tentando implementar isso comHttp
eObservable
. Meu problema é que eu não seicomo mesclar váriosObservable
s dependendo de quantas páginas de itens existem efinalmente retorne umObservable
que meu componente pode se inscrever.
Aqui é onde eu cheguei com minha implementação atual do TypeScript:
// NOTE: Non-working example!
getAllItems(): Observable<any[]> {
// array of all items, possibly received with multiple requests
const allItems: any[] = [];
// inner function for getting a range of items
const getRange = (range?: string) => {
const headers: Headers = new Headers();
if (range) {
headers.set('Range', range);
}
return this.http.get('http://api/endpoint', { headers })
.map((res: Response) => {
// add all to received items
// (maybe not needed if the responses can be merged some other way?)
allItems.push.apply(allItems, res.json());
// partial content
if (res.status === 206) {
const nextRange = res.headers.get('Next-Range');
// get next range of items
return getRange(nextRange);
}
return allItems;
});
};
// get first range
return getRange();
}
No entanto, isso não funciona. Se eu entendi direito, umObservable
é retornado como o valor da inicialObservable
e não a matriz de itens.