简体   繁体   English

数字数组将转换为键值对数组;

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

I created this function in an Angular4 app: 我在Angular4应用中创建了此函数:

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. 然后,我需要将Course_id属性存储到数组中。

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. 谢谢,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. 其次,您正在循环内执行asyc操作,因此,在第二个控制台日志出现时,数据可能还不存在。

A better solution would be to use Observable.forkJoin to wait for all async requests and then map the data. 更好的解决方案是使用Observable.forkJoin等待所有异步请求,然后映射数据。

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))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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