Harshit Mulchandani
Harshit Mulchandani

Reputation: 101

Synchronous GET requests in angular2

I want to make a component in Angular2 where in a loop of 50 iterations will execute and I want to send GET requests only in the even iterations. Now I want to send synchronous GET requests such that unless and until data from the even iteration is not received, the loop should wait and not enter the odd iteration. Any ideas on how that can be done?

Here's the function written in the service - `

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

Here's the output- And here's the output -

I hope the problem is clear now.The responses should come in order and the even iteration console message should be displayed only when its odd counterpart has returned the object. Please suggest a solution.

Upvotes: 4

Views: 7391

Answers (1)

Harshit Mulchandani
Harshit Mulchandani

Reputation: 101

So with the help of my instructor, we finally achieved what we wanted.We sent asynchronous requests and returned the responses as observables .Now we concatented these observables,returned on alternated loop iterations and achieved the following output- output

This is my code-

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

    }
  }

Upvotes: 2

Related Questions