typescript 在 for 循环 Angular2 Django 中获取多个可观察请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37530799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
multiple get observable requests in a for loop Angular2 Django
提问by Johnny Chan
I am trying to perform several get requests using Angular2 in Django/python.
我正在尝试在 Django/python 中使用 Angular2 执行几个 get 请求。
I am able perform an API request and get a list of users to find the id of the current user. I then perform a .flatMap
operation to perform a second request to get a list of all comments. I compare the userId to the list of comments to select only the comments made by the user. All data I receive is JSON.
我能够执行 API 请求并获取用户列表以查找当前用户的 ID。然后我执行一个.flatMap
操作来执行第二个请求以获取所有评论的列表。我将 userId 与评论列表进行比较,以仅选择用户发表的评论。我收到的所有数据都是 JSON。
At this point, I am trying to get the Article that belongs to each comment made. But when I try to run a function to try to get data in a for loop, the request does not even get performed.
在这一点上,我正在尝试获取属于每个评论的文章。但是当我尝试运行一个函数来尝试在 for 循环中获取数据时,该请求甚至没有执行。
Heres my service:
这是我的服务:
import {Injectable} from "angular2/core";
import {Http, Headers, Response} from "angular2/http";
import 'rxjs/Rx';
import {Observable} from "rxjs/Observable";
@Injectable()
export class DataService {
profileUserName: profileUserName = document.getElementsByClassName('profile-user-name')[0].children[0].innerHTML;
userComments: [];
constructor (private _http: Http) {}
getUsers(): Observable<any> {
return this._http.get('/api/v1/users/?format=json')
.map((res: Response) => {
this.userList = res.json();
// select only comments made by current user
for (i = 0; i < this.userList.length; i++) {
if(this.profileUserName == this.userList[i].username){
this.userId = this.userList[i].url
}
}
})
.flatMap(() => this._http.get('/api/v1/article_comments/?format=json')).map((res: Response) => {
this.commentList = res.json();
let userComments = [];
for (i = 0; i < this.commentList.length; i++) {
if (this.commentList[i].user == this.userId) {
userComments.push(this.commentList[i])
}
}
this.userComments = userComments;
return this.parseArticleComments();
})
}
parseArticleComments() {
for (i = 0; i < this.userComments.length; i++) {
this.currentSelection = this.userComments[i];
this.getArticleComments(this.currentSelection)
}
// response should/is returned here to the appComponent
return this.userComments
}
// currently not performing any http requests
getArticleComments(currentSelection): Observable<any> {
// currentselection.article == http://localhost:8000/api/v1/articles/10/?format=json
return this._http.get('currentselection.article')
.map((res: Response) => {
console.log('entered');
currentSelection.articles = res.json();
return currentSelection.articles;
})
}
}
Heres my app.component:
这是我的 app.component:
import {Component, OnInit} from 'angular2/core';
import {DataService} from './data.service.ts';
@Component({
selector: 'http-app',
template: `
<div>
<button (click)="logGetRequest()">Log Reqeust</button>
<ul>
<li *ngFor="let comment of commentList"> {{ comment.article }} </li>
</ul>
</div>
`,
providers: [DataService]
})
export class AppComponent{
commentList: string;
constructor ( private _dataService: DataService) {}
//get list of users to find user ID
getUserList = this._dataService.getUsers()
.subscribe(
data => this.commentList = (data),
error => console.error(error)
);
logGetRequest() {
console.log(this.commentList);
}
}
Any suggestions or ideas as to why I cannot perform these requests?
关于为什么我不能执行这些请求的任何建议或想法?
回答by Thierry Templier
The problem is that the parseArticleComments
method is asynchronous because it's based on the getArticleComments
one. I would try something like that.
问题在于该parseArticleComments
方法是异步的,因为它基于该方法getArticleComments
。我会尝试这样的事情。
The Observable.forkJoin
method wait for all observables to be execute (similar to Promise.all
). The Observable.of
method returns a raw observable for a specific value.
该Observable.forkJoin
方法等待所有 observable 被执行(类似于Promise.all
)。该Observable.of
方法返回一个特定值的原始 observable。
parseArticleComments() {
var articleCommentsObservables = this.userComments.map(userComment => {
return this.getArticleComments(userComment);
});
return Observable.forkJoin(articleCommentsObservables);
}
and call it into the callback of a flatMap operator:
并将其调用到 flatMap 运算符的回调中:
.flatMap(() => this._http.get('/api/v1/article_comments/?format=json'))
.flatMap((res: Response) => {
(...)
return Observable.forkJoin([
Observable.of(this.userComments),
this.parseArticleComments()
]);
})
.map(result => {
var userComments = result[0];
return userComments;
})