0

When I do console.log( accomdationSearchResultsData.length ); I always get length of 0 in the console but there are actually 2 objects

Object

enter image description here

Sample Code

accommodationById() {
    var accomdationSearchResultsData = [];
    var hotelSearchCount = 0;

    this.api.accommodationById( this.accomodationId ).subscribe( accomdationResponse => {
        var accomdation_id, accomdation_type, accomdation_hotel, accomdation_id, accomdation_rate, accomdation_hotel_id, accomdation_hotel_name, accomdation_hotel_city, accomdation_hotel_street, accomdation_hotel_state, accomdation_hotel_checkin_time, accomdation_hotel_checkout_time;

        var accomdation_id = accomdationResponse.id;
        var accomdation_type = accomdationResponse.name;
        this.accomodationType = accomdation_type;

        for (var i = 0; i < accomdationResponse.Rooms.length; i++){
          accomdation_hotel = accomdationResponse.Rooms[i].hotel;
          accomdation_rate = accomdationResponse.Rooms[i].rate;

          this.api.getHotelByAPI( accomdation_hotel ).subscribe( hotelResponse => {

            accomdation_hotel_id = hotelResponse.id;
            accomdation_hotel_name = hotelResponse.name;
            accomdation_hotel_city = hotelResponse.city;

            accomdationSearchResultsData.push({
              accomdation_id: accomdation_id,
              accomdation_type: accomdation_type,
              accomdation_hotel: accomdation_hotel,
              accomdation_rate: accomdation_rate,
              accomdation_hotel_id: accomdation_hotel_id,
              accomdation_hotel_name: accomdation_hotel_name,
            });
          });
        }

        this.accomodationResults = accomdationSearchResultsData;
        console.log( accomdationSearchResultsData.length );
    });
}
Red Virus
  • 1,633
  • 3
  • 25
  • 34
  • 2
    subscribe method is asynchronous so you should move the console call within subscribe method – Vladu Ionut Feb 04 '17 at 10:20
  • 1
    See the linked question's answers for the main issue. The reason you're seeing what you're seeing in the console is here: http://stackoverflow.com/questions/38660832/element-children-has-elements-but-returns-empty-htmlcollection – T.J. Crowder Feb 04 '17 at 10:27

1 Answers1

-2

try this

setTimeout(function () {
        console.log(accomdationSearchResultsData.length);
    }, 2000);

i think that you just log it before process is done.

BARNI
  • 162
  • 2
  • 10
  • 2
    This is a very fragile solution, it waits just 2 seconds. If your API call takes longer than 2 seconds, this won't work. – Soviut Feb 04 '17 at 10:19
  • I only gave him code because of testing. this is not a solution, i know this. Now he understood that problem is timing and he should run some onload function. – BARNI Feb 04 '17 at 10:21