0

I have a service which gets data from API : https://jsonplaceholder.typicode.com/posts/1

but i can not store data in variable

Code : Service.ts

public urlServer : string = "https://jsonplaceholder.typicode.com/posts/1";

public getAllProjectsFromAPI() : Observable<any> {
   return this.http.get( this.urlServer, { responseType: 'json' } ); 
}

Component.ts

constructor( private projects : ProjetsService ) { }

  ngOnInit() {
    this.projects.getAllProjectsFromAPI().subscribe( data => this.test = JSON.stringify( data ) );
    console.log( this.test );
  }

I try to console test var and i get undefined

wyllisMonteiro
  • 61
  • 3
  • 11

1 Answers1

3

Your are trying to log a value which is not yet computed.

// this block is asynchronous
this.projects.getAllProjectsFromAPI().subscribe( 
  data => this.test = JSON.stringify( data )
);
// this line is synchronous
console.log( this.test );

Execute your code in the asynchronous block:

this.projects.getAllProjectsFromAPI().subscribe(data => { 
  this.test = JSON.stringify(data);
  console.log(this.test)
});

Note that I added {} in order to execute multiple lines in the observable callback.

Ploppy
  • 14,810
  • 6
  • 41
  • 58
  • Thanks for answer, i would like show test variable in my html file is it possible in my case. – wyllisMonteiro Aug 12 '18 at 17:44
  • In your component template file: `
    {{test}}
    `. Please accept the answer if it fits your need.
    – Ploppy Aug 12 '18 at 17:46
  • Thank you but can i have more details.It work's in HTML file but i don't understand why. Indeed the code that i want to execute is asynchronous and HTML too ? – wyllisMonteiro Aug 12 '18 at 17:51
  • 1
    I really encourage you to take take a look at the official tutorial to better understand Angular https://angular.io/tutorial – Ploppy Aug 12 '18 at 19:43
  • It will work in HTML file because the value is already loaded. Assign a dummy value on `{{test}}` before calling the API and then you will see that the value will change asynchronously. – Gerald Gonzales Aug 13 '18 at 02:47