Observable inside a for

0

I am practicing ionic2, I am doing services with observables, in one part I made a for and within that for call another service but it seems that it stops the for and is counting the total of the array. Is it because of the observable that stops it? I show you how I am doing it:

menu.ts

getMenusAjax():Observable<any>{
  return this.http.get('http://localhost:3000/menu/todos')
    .map(res => res.json());
}

contenido.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()

export class contenidoServices{
  constructor(public http: Http){}

  getContenidoImagenes(id):Observable<any>{
    return this.http.get('http://localhost:3000/imgcont/${id}')
        .map(res => res.json());
  }
}

page2.ts

import { Component } from '@angular/core';

import { NavController, NavParams } from 'ionic-angular';

import { Me } from '../../app/commons/me';
import { MenuServices } from '../../app/services/menu';
import { contenidoServices } from '../../app/services/contenidos';

@Component({
 selector: 'page-page2',
 templateUrl: 'page2.html'
})

export class Page2{

  selectedItem: any;

  constructor(
   public navCtrl: NavController,
   public navParams: NavParams,
   private menu: MenuServices,
   private contenido: contenidoServices
  ){
    var contenidoDate = navParams.get('item');

    for (var j = 0; j < contenidoDate.length; ++j) {
      console.log(j);
      let images = contenido.getContenidoImagenes(contenidoDate[j].id);

      images.subscribe(
        res => {
          console.log(j);
          if(res != 2) {
            console.log(res);
            console.log(contenidoDate[j]);
          }
        },
        err => {console.log(err);}
      );
    }
    this.selectedItem = navParams.get('item');
  }
}

Result in console, numbers 0 and 1 print before calling the service and 2 prints when the service has already been called

    
asked by Albert Arias 05.04.2017 в 20:06
source

2 answers

0

Exactly because of the observables, they are a promise that you get that information but not immediately, in this way you do not block the page with waiting.

If you want to use multiple observables there are several tools, in your case I think you will work a merge
link

    
answered by 05.04.2017 в 22:37
0

The implementation is not appropriate since you are saturating the back with many requests, I recommend that in a single url keep all the information of the images and so with a single observable you get everything, imagine you have more than 100. Your whole system would become unstable, that's why it's already giving you problems.

    
answered by 11.04.2017 в 20:16