Home > OS >  How to get data from an observable array?
How to get data from an observable array?

Time:12-14

I have an application built using a Python backend and an Angular frontend. The app I'm building gets FIFA players from a MongoDB using the function getLoyalPlayers:

Here is the loyalty.component.ts:

import { Component } from "@angular/core";
import { WebService } from './web.service';

@Component({
  selector: 'loyal',
  templateUrl: './loyal.component.html',
  styleUrls: ['./loyal.component.css']
})
export class LoyalComponent {
  constructor(public webService: WebService) {}

  ngOnInit() {
    this.player_list = this.webService.getLoyalPlayers();
  }

  player_list: any = [];
}

This is the web.service.ts

  getLoyalPlayers(loyalPage: number) {
    return this.http.get('http://localhost:5000/api/v1.0/loyal-players');
  }

This data is then displayed using async in loyalty.component.html like so:

<div *ngFor="let player of player_list | async">
    <!-- Items inside this array are then accessed like -->
    {{ player.short_name }}
</div>

I am trying to access the items in this array in the typescript file like so:

ngOnInit() {
    if (sessionStorage['loyalPage']) {
      this.page = Number(sessionStorage['loyalPage']);
    }

    this.player_list = this.webService.getLoyalPlayers(this.page);

    console.log(this.player_list.short_name)
}

But this gives me an result of undefined:

enter image description here

How do I get this data to be returned?

CodePudding user response:

When you work with observables you has tree different aproach

  1. Use pipe async (you do it when use in .html |async)
  2. Subscribe to the observable, store the result in a variable and iterate over this variable. Rememeber that the variable only get value after the call is completed
    this.webService.getLoyalPlayers(this.page).subscribe((res:any)=>{
        this.player_list=res;  //<--see that here player_list is the "object"
        //here you can use 
        console.log(this.player_list)
     })
      //but you can not use here
        console.log(this.player_list)
  1. Use pipe tap to store the value in the variable. the rxjs operator tap is executed after the observable has subscribted and completed -the pipe async is who makes this work
    //see that this.player_list$ is an Observable
    //In Angular is common use the "$" to indicate that it's a observable
    this.player_list$=this.webService.getLoyalPlayers(this.page)
       .pipe(tap((res:any)=>{
        this.player_list=res;
        //here you can use 
        console.log(this.player_list)
     })))
  • Related