在for循环Angular2 Django中多次获取可观察请求

时间:2016-05-30 17:13:06

标签: javascript django typescript angular rxjs

我正在尝试使用Django / python中的Angular2执行几个get请求。

我可以执行API请求并获取用户列表以查找当前用户的ID。然后,我执行.flatMap操作以执行第二个请求以获取所有注释的列表。我将userId与注释列表进行比较,以仅选择用户所做的注释。我收到的所有数据都是JSON。

此时,我正在尝试获取属于每个评论的文章。但是当我尝试运行一个函数来尝试在for循环中获取数据时,请求甚至都没有执行。

继承我的服务:

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;
        })
  }
}

继承我的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);
  }
}

关于我无法执行这些请求的任何建议或想法?

1 个答案:

答案 0 :(得分:1)

问题是parseArticleComments方法是异步的,因为它基于getArticleComments方法。我会尝试类似的东西。

Observable.forkJoin方法等待执行所有可观察对象(类似于Promise.all)。 Observable.of方法返回特定值的原始observable。

parseArticleComments() {
  var articleCommentsObservables = this.userComments.map(userComment => {
    return this.getArticleComments(userComment);
  });
  return Observable.forkJoin(articleCommentsObservables);
}

并将其调用到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;
})