我正在从 angular2 应用调用外部 API,它以分页形式提供数据。响应看起来像这样
{
next: "next_url",
results: []
}
我可以使用 Rxjs 或 Angular2 的内置 Http 类(它返回一个可观察对象)来连接下一个 url 的结果,直到
{
next: null,
results: []
}
我觉得我需要使用 concatMap 运算符,但我还没有弄清楚语法,因为我是响应式扩展的新手。
最佳答案
下面是我的做法:
import {Component} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
@Component({
selector: 'my-app',
template: `<h2>Results: {{out | async | json}}</h2>`,
})
export class App {
constructor() {
this.out = this.getAllResults();
}
getAllResults(startIdx = 0) {
return this.getData(startIdx)
.concatMap(data => {
if (data.next) {
return this.getAllResults(data.next)
.map(resultsToJoin => [...data.results, ...resultsToJoin]);
} else {
return Observable.of(data.results);
}
});
}
// pretend this is our http call
getData(idx : number) {
const data = [{
next: 1,
results: [1, 2]
}, {
next: 2,
results: [3, 4]
}, {
next: null,
results: [5, 6]
}];
return Observable.of(data[idx]);
}
}
关于angular - 在 angular2 中使用 Rxjs 连接分页响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34542852/