I'm encountering difficulties with updating a global variable in Angular 7 by using TypeScript.
I am utilizing a service that retrieves JSON data from a database via 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 functioning properly and I am able to retrieve the desired data, then I call the service in the component
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
}
I would appreciate insights on why my global variable "listeDossiers" is only updated within the subscribe function.
I attempted using a subject for the "listeDossier" and refreshing it right after changing the variable within the subscription, but without success.
Thank you for your assistance.