angular2 中的同步 GET 请求

Synchronous GET requests in angular2

我想在 Angular2 中创建一个组件,其中将执行 50 次迭代的循环,并且我只想在偶数次迭代中发送 GET 请求。现在我想发送 同步 GET 请求 这样除非且直到未收到来自偶数迭代的数据,循环应该等待并且不进入奇数迭代。关于如何做到这一点的任何想法?

这是服务中编写的函数 - `

     getUser() {
     for(let i = 1;i < 10;i++) {
      if (i % 2 != 0) {         
      var resp =this.http.get('https://jsonplaceholder.typicode.com/users/'+i)
          .map(res=> res.json());

      if(resp){
      resp.subscribe(res=>{
        console.log(res);
      });
    }

  }
  else{
    console.log("even iteration");
  }
}

这是输出-

我希望问题很清楚 now.The 响应应该按顺序出现,偶数迭代控制台消息应该仅在其奇数对应项返回对象时显示。请提出解决方案。

所以在我的导师的帮助下,我们终于实现了我们 wanted.We 发送异步请求并将响应作为可观察对象返回的结果。现在我们连接这些可观察对象,返回交替循环迭代并获得以下输出 -

这是我的代码-

service.ts -

getUser(i: number): Observable<any>{
  return this.http.get('https://jsonplaceholder.typicode.com/users/' + i)
    .map(res => res.json());

 }

component.ts -

import {Component, OnInit} from '@angular/core';
import {AppService} from "./app.service";
import {Observable} from 'rxjs/Rx';

 @Component({
 selector: 'app',
 templateUrl: './app.component.html'
 })
 export class AppComponent implements OnInit {


  name:string;
  call: Observable<any>;

   constructor(private _service: AppService) {}

    public ngOnInit() {

   }

  getUser(){
    this.call = Observable.concat();
   for(let i=1;i<=10;i++) {
     if(i%2!=0){
       this.call = this.call.concat(this._service.getUser(i));
      }
     else{
       this.call = this.call.concat(Observable.create(x=> {x.next(i)}).first());
      }
    }
        this.call.subscribe(res=>console.log(res));

    }
  }