0

I am fetching data from PHP API, But the variable after subscribe is empty in component.ts but, while using in component.html it displays data. I want to modify after fetching from API.

In service.ts:

get_tournaments(){
    return this.http.get("http://localhost/Website/api/tournament/read.php")
    .map(res=>res.json());
  }

In component.ts:

tournaments:Object[] = [];

ngOnInit() {  
    this.ongoing_ser.get_tournaments() 
    .subscribe(value=>this.tournaments=value);
    console.log("Main:",this.tournaments); <-- this is empty
}

In component.html:

it displays everything correct as required. 

I want to modify the data fetched from API and then display in html

0

2 Answers 2

1

@Sudhindra Purohit Javascript is synchronous so it will to wait to complete subscribe your request. So that It will return empty in console.

If you want to modify your data then you can do like below

 this.ongoing_ser.get_tournaments() 
    .subscribe(value=> { this.tournaments=value;
     // DO here what ever you want with tournaments
     this.tournaments = this.tournaments.map(tour => {
       console.log(tour);
      }
 });
Sign up to request clarification or add additional context in comments.

Comments

0

You need to assign the value to the component variable and then alter it or display it using interpolation {{}}

In the componenet.ts

ngOnInit() {

    this.ongoing_ser.get_tournaments() 
        .subscribe(
            (data:any)=>{
                this.data=data;
                //you can do the data modification here 
            })

  }

In component.html

<div>{{data}}</div>

This will display the data in HTML

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.