3

i'm having issues with changing global variable in Angular 7, using TypeScript.

I am using a service that collects JSON data from a database through a Restful API

The service :

export class myService {
  constructor(private client : HttpClient) { }

  dossierSubject = new Subject();
  private dossiers : any[];

  getExtract(){
    this.client.get<any[]>('http://localhost:9090/dossiers')
    .subscribe(
      (response) => {
        console.log("Data acquisition in progress");
        this.dossiers = response;
        this.emitDossierSubject();
        console.log('Received data ' + response);
      },
      (error) => {
        console.log('Error ! : ' + JSON.stringify(error));
      }
    );
  }

   emitDossierSubject(){
    this.dossierSubject.next(this.dossiers.slice());
  }

MyService is working well and i can get the Data i'm looking for, then i call the service into the componnent

The component

 export class tabComponent implements OnInit {

  constructor(private dossierService : myService) { }

  private dossierSubscription : Subscription;
  private listeDossiers : any[];

  ngOnInit() {
    this.spinnerStatus = true;
    this.dossierService.getExtract();
    this.dossierSubscription = this.dossierService.dossierSubject.subscribe(
      (dossiers : any[]) => {
        this.listeDossiers = dossiers;
        console.log(listeDossiers); //dossiers [object][object]
        this.spinnerStatus = false;
      }
    );
    console.log('Received data : '+ this.listeDossiers);  //undefined
  }

Please, i would like to know why my global variable "listeDossiers" is changed only inside the subscribe function.

I tried using a subject for the "listeDossier" and refresh it juste after i change the variable inside subscription, without success.

Thanks for your help.

Dalito
  • 31
  • 2

1 Answers1

-1

I believe the console.log(listeDossiers); should be console.log(this.listeDossiers);

And the console.log outside the subscribe will be called but won't wait for the http request, you try to print it as part of the ngOnInit() function without waiting, however it's only within the subscribe that you actually assign it

Jojofoulk
  • 2,127
  • 1
  • 7
  • 25
  • 1
    Thank you Jojofoulk, i understand, is there any way that would allow me to assign the global variable in order to use it afterward ? – Dalito Apr 26 '19 at 11:34