3

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

}

1 Answer 1

8

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.