0

I am trying to loop through an array of incoming data so that I can display the information on a map in leaflet!

here is my class:

export class OpenStreetMapComponent implements OnInit {
  @Output() private add = new EventEmitter();
  @Output() private edit = new EventEmitter<number>();
  artworkList: Artwork[];

the data as it comes in is stored in the artworkList array

constructor(private artworkService: ArtworkService) { }
  ngOnInit() {
    this.refresh();
  }

  refresh() {
    this.artworkService.retrieveAll().then(
      artworkList => this.artworkList = artworkList
    );
    for (let artwork of this.artworkList) {
      console.log(artwork.name);
  }

for some reason i keep getting this error is my console:

ERROR TypeError: "_a is undefined"

1
  • 1
    You retrieve the data through an async call as promise, but you iterate over the array syncronously. You should move your for loop into the then call. Commented Jan 23, 2019 at 13:10

2 Answers 2

2

Your loop operates synchronously, whereas you fetch the data it iterates over asynchronously. You will have to move the actual loop into the then-block so that you do not access a possibly undefined value.

constructor(private artworkService: ArtworkService) {
}

ngOnInit() {
  this.refresh();
}

refresh() {
  this.artworkService.retrieveAll().then((artworkList) => {
    this.artworkList = artworkList;
    for (let artwork of this.artworkList) {
      console.log(artwork.name);
    }
  });
}
Sign up to request clarification or add additional context in comments.

Comments

1

.retriveAll() method is a promise, you must await this method before attempting to make use of this.artworkListor you can place the following into the .then part of the call.

for (let artwork of this.artworkList) {
  console.log(artwork.name);
}

Currently, the loop is being run asynchronously along with the call to your method that returns a Promise, which is attempting to loop through an empty this.artworkList, causing the issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.