【发布时间】:2017-08-04 22:07:06
【问题描述】:
我刚刚使用 Angular2 一周大!
基本上有 2 个 API 调用。
- 第一个 API 调用给我一个 json 对象的数组 (queryResults)。 (第一次订阅)
- 在视图中显示该数组。
- 遍历 (queryResults) 数组并选择一个特定的键:每个数组元素中的值对 (queryResults[i].oldLastSeen)。
- 将该值 (oldLastSeen) 作为请求参数传递给另一个 API,从而得到一个字符串 (newLastSeen)。 (第二次订阅)
- 在 queryResult 中将 oldLastSeen 替换为 newLastSeen
由于 Observable 的异步特性,问题出现在第 5 步。我无法访问内部订阅内的queryResults[i].oldLastSeen,基本上是未定义的。因此 lastSeen 不会更新。
首先调用getLastSeen(),
代码如下所示:
temp: any[];
rows: any[];
getLastSeen() {
this._someService.getQueryResults(this.query)
.subscribe(queryResults => {
this.rows = queryResults;
this.updateLastSeen(this.rows);
});
}
private updateLastSeen(rows) {
this.temp = rows; //temp: any[];
for(var i=0; i<this.temp.length; i++) {
if(this.temp[i].id != null || this.temp[i].oldLastSeen != null) {
//Some operations here
this._someService.getNewLastSeen(this.temp[i].oldLastSeen)
.subscribe(
newLastSeen => {
this.rows[i].oldLastSeen = newLastSeen; //This doesnot happen!
},
error => alert(error),
() => console.log("Finished.")
);
}
}
}
从 2 天以来一直在敲我的头,遇到了 flatMap、switchMap 等。但对它们的使用高度怀疑。
更新:工作代码:
我按照 Bryan 的反馈,对他建议的代码进行了一些修改。这对我有用:
this._someService.getQueryResults(this.query)
.do(qr => {this.rows = qr;})
.flatMap(queryResults => Observable.from(queryResults))
.filter(queryItem => queryItem["id"] != null || queryItem["oldLastSeen"] != undefined)
.do(queryItem => { // did some operations/ manipulations here})
.mergeMap(queryItem => this._someService.getNewLastSeen(this.queryItem["oldLastSeen]),
(queryItem, newLastSeen) => [queryItem, newLastSeen])
.subscribe(([queryItem, newLastSeen]) => {
queryItem.oldLastSeen = newLastSeen
});
【问题讨论】:
-
是在等待用户的输入还是发生了什么??
-
getLastSeen() 从 ngOnInit() 调用。没有用户输入。
标签: angular http request angular2-observables angular2-http