Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Observable to Array

The following does not output array to console. Scoping incorrect???

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Broker } from './broker';

@Injectable()
export class BrokerSurveyService {

  brokers: Broker[] = [];

  constructor(private http: HttpClient) { 
    this.getBrokers().subscribe((brokers) => { 
      this.brokers = brokers;
    });
    console.log(this.brokers); # Does NOT output to console
  }

  getBrokers() {
    return this.http.get<Broker[]>('http://www.example.com/brokers.json');
  }

}

This outputs the array to the console because it sent to console immediate after assignment. Is this scope different? I'm confused as to why.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Broker } from './broker';

@Injectable()
export class BrokerSurveyService {

  brokers: Broker[] = [];

  constructor(private http: HttpClient) { 
    this.getBrokers().subscribe((brokers) => { 
      this.brokers = brokers;
      console.log(this.brokers); # Outputs to console
    });
  }

  getBrokers() {
    return this.http.get<Broker[]>('http://www.example.com/brokers.json');
  }

}
like image 748
Michael Niño Avatar asked Jun 16 '26 19:06

Michael Niño


1 Answers

It is correct,

Since the service call is asynchronous, the data does not arrive immediately when the subscribe is called. Rather, when the response is returned from the service, the callback function defined as the argument to the subscribe method is then called.

That's why the console.log within the Subscribe works.

If you want to use the array somewhere in your code, call using another method

constructor(private http: HttpClient) { 
    this.getBrokers().subscribe((brokers) => { 
      this.brokers = brokers;
      useBroker(this.brokers);
    });
 }

useBroker(brokers:any){
   console.log(brokers);
}
like image 159
Sajeetharan Avatar answered Jun 18 '26 15:06

Sajeetharan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!