PR7
PR7

Reputation: 1912

Angular 2, Unable to iterate through array

I have a subscribed to a FirebaseObjectObservable to get value of a property of an object from my firebase database. This property can contain multiple values so I stored the values in a local array variable.

But I am unable to iterate through this local array variable using forEach. So I console.log this array variable. This variable seems to have json format maybe thats why I am unable to iterate. Please help me find a way to iterate through this variable.

* Code and Console Images :

Code Screenshot

Console Screenshot

* Edit *

I shifted the code inside the subscribe method to iterate.

getAttachments() {
this.assignment.subscribe(asnDetails => {
  if (asnDetails.fileKey) {
    this.fileKeys.push(asnDetails.fileKey);
    this.fileKeys[0].forEach(asnFileKey => {  // <---- shifted this forEach loop inside subscribe 
      this.asnFiles = this._getAsnService.getAssignmentFiles(asnFileKey);
      this.asnFiles.subscribe(file => {
        this.fileNames.push(file.name);
      });
    });
  }
});
}

Upvotes: 0

Views: 622

Answers (3)

user663031
user663031

Reputation:

The this.fileKeys value is available only within the subscribe handler. That's basic to asynchronous programming. Your console log is immediately after the subscribe, and is executed before the subscription has had a change to fire.

Upvotes: 2

Ced
Ced

Reputation: 17417

You have one nested array in your screenshot. The first one is of length 1 and the nested one is of length two. So you can access array[0].forEach(item => console.log(item))

Upvotes: 1

Garamaru
Garamaru

Reputation: 116

Sadly, I can't comment. It's not an angular or firebase problem.
It's a normal array, based on your console screenshot.
Have you tried to iterate through this.fileKeys?
If someone could post this as a comment, I would delete this as an answer.

Upvotes: 0

Related Questions