Home > Software engineering >  Send Angular API GET request value to a variable
Send Angular API GET request value to a variable

Time:12-14

I am trying to display the data of an object on Angular like so
{{myCharactere && myCharactere.statistics && myCharactere.statistics[stat.key] || ''}}. The object is issue from an API GET request but I'm not able to send it's value to my local variable myCharactere. Thank you for helping me out!

Here is what I tried

getInfos() {
    return this.myService.getAllInfosById(this.myService.getIdPersonnageByName("Xefoul Snaromers")).subscribe(v => { this.myCharactere = v; });
  }

ngOnInit(): void {
    this.getInfos();
  }

CodePudding user response:

Summarized from comments:

In your component you can use

serviceName.getAllInfosById("demochar").subscribe(console.log)

to manually make the request to the API and log the result. Please be aware that this.http_client.get<ICharactere>(myUrl) returns a cold observable. This means that nothing will be done until you actually call .subscribe to it.

Best practice: Usually when you want to display data from an observable in your HTML template you define an observable and subscribe to it using async pipe.

The way to do this is to first define the observable in your component, like: info$ = this.serviceName.getAllInfosById("demochar").

Now in your HTML template you can use {{ (info$ | async).name }} to first subscribe to the observable (async pipe does this for you) and display the name property of the emitted value.

CodePudding user response:

If you are actually using an observable like this.http_client.get<ICharactere>(myUrl), another way is to await the return value and store it in a this.myCharactere:

async getInfos(): void {
   this.myCharactere = await firstValueFrom(this.myService.getAllInfosById(this.myService.getIdPersonnageByName("Xefoul Snaromers")));
}
  • Related