ottz0
ottz0

Reputation: 2605

Looping through data from returned service

I have a subscribed to a service and need to loop through data returned from the service before outputting it to my view.

If I console log it out I get all the data requested but when I try to output it in the view I only get the last record in the data.

export class SandboxComponent implements OnInit {

  statusList;
  errorMessage;
  constructor(private dataService : DataService) { }

  ngOnInit() {
   this.getStatusTag();
  }

  getStatusTag(){
    this.dataService.getStatusAPI()
    .subscribe(
        (data) => {
            for(let myVar of data){
              this.statusList = myVar;
              console.log(this.statusList);
            }
        },
        error => this.errorMessage = <any>error);
  }

}

Upvotes: 0

Views: 37

Answers (2)

You should use map before subscribe to log single data and make some transformation to your data.

getStatusTag(){
    this.dataService.getStatusAPI()
    .map(response =>{
     // below you can log a single data
     console.log(response);
     return response.json()
     })
    .subscribe(
        (data) => {
             // below you can log all data
             console.log(data);
             this.statusList = data;
        },
        error => this.errorMessage = <any>error);
  }

Upvotes: 0

Sunnny
Sunnny

Reputation: 99

this.statusList = myVar; Should be array

  this.statusList.push(myVar);

Upvotes: 1

Related Questions