简体   繁体   中英

Array of numbers gets converted to an array of key-value pairs;

I created this function in an Angular4 app:

enrollmentCheck() {

this.allCourses.forEach(course => {
  this._courses.getCurrentEnrolment(course.slug).subscribe(res => {
    if(res.length > 0){
      this.enrolledCourses.push(res[0].course_id);
      console.log(this.enrolledCourses);
    }
  })
});
console.log(this.enrolledCourses);
}

It is supposed to iterate through an array of objects and check if the user is enrolled to any of them.

The first bit works well, the subscribtion gives me the right data (res). I then need to store the property course_id into an array.

The first log (inside the loop), seems to work fine. I get

[1]
[1,2]
[1,2,5]
[1,2,5,7]

as outputs, one for each time the loop is executed.

Problem is that the second log (outside the loop), will output something like:

[
 0: 1
 1: 2
 2: 5
 3: 7
]

rather than

[1,2,5,7]

as I would like, for I will need to iterate through this array, and I cannot find a way to do it with the one I get.

Can anyone help? I apologise if this may seem a silly question to someone, but any help would be really appreciated.

Thanks, M.

There are a few problems with your method. First of all you're creating subscriptions inside a loop, that's a bad idea because you're never completing them. Second you're doing asyc operations inside the loop therefore at the time the second console log appears the data might not be there yet.

A better solution would be to use Observable.forkJoin to wait for all async requests and then map the data.

For example

enrollmentCheck() {
  Observable.forkJoin(
    this.allCourses.map(course => {
      return this._courses.getCurrentEnrollment(course.slug);
    }
  ).map(res => {
    return res
       .filter(enrollment => enrollment.length > 0)
       .map(enrollment => enrollment[0].course_id)
  }).subscribe(data => console.log(data))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM