简体   繁体   English

角度:Observable.subscribe取消同步怪异错误

[英]Angular: Observable.subscribe desync weird error

I tried to do a lot of queries in a loop using this: 我试图使用此循环执行很多查询:

  buildQuestions() { for(var i = 0;i<this.sections.length;i++) { this.serviceQue.getQuestionsBySectionId(this.sections[i].section_id) .subscribe(rt => this.sections[i].questions=rt, er => console.log(er), () => console.log("OK")); } } 

The problem is that when subscribe call the line rt => this.sections[i].questions=rt, i doesnt have the same value, then send error because for some i, this.sections[i] is undefined. 问题是,当订阅呼叫rt => this.sections [i] .questions = rt时,我没有相同的值,然后发送错误,因为对于某些i,this.sections [i]未定义。

For example if i have 1 section and i at the start is 0, then it call this.serviceQue.getQuestionsBySectionId(this.sections[i].section_id) with i = 0, but .subscribe(rt => this.sections[i].questions=rt is excecuted with i = 1, i tried to do something like manual sync using this code: 例如,如果我有1个小节,而我的开头是0,则它以i = 0调用this.serviceQue.getQuestionsBySectionId(this.sections [i] .section_id),但是.subscribe(rt => this.sections [i ] .questions = rt在i = 1下执行,我尝试使用此代码执行类似手动同步的操作:

  buildQuestions() { var last = -1; for(var i = 0;i<this.sections.length;) { if(last!=i) { last = i; this.serviceQue.getQuestionsBySectionId(this.sections[i].section_id) .subscribe(rt => this.sections[i].questions=rt, er => console.log(er), () => i++); } } } 

but, for some weird reason, when i do that, this.serviceQue.getQuestionsBySectionId(this.sections[i].section_id) never send a response and do a infinite loop, if i use the first code it send a response, but if i use the second code it never send a response. 但是,出于某些奇怪的原因,当我这样做时,如果我使用第一个代码发送响应,则this.serviceQue.getQuestionsBySectionId(this.sections [i] .section_id)永远不会发送响应并执行无限循环。我使用第二个代码,它从不发送响应。

someone can help me? 有人可以帮助我吗?

Yes, that's exactly how JS works. 是的,这就是JS的工作方式。 When the callback is executed the loop has already finished so i will have the length value. 当执行回调时,循环已经完成,所以我将获得长度值。 You have to put your code in a closure: 您必须将代码放在闭包中:

buildQuestions() {

    this.sections.forEach(section => {
        this.serviceQue.getQuestionsBySectionId(section.section_id)
            .subscribe(rt => section.questions = rt,
                er => console.log(er),
                () => console.log("OK"));
        }
    });      
}

More info about this issue: Here you have the explanation of why is this happening: https://hackernoon.com/how-to-use-javascript-closures-with-confidence-85cd1f841a6b 有关此问题的更多信息:在这里,您对发生这种情况的原因进行了解释: https : //hackernoon.com/how-to-use-javascript-closures-with-confidence-85cd1f841a6b

By the way, this is a classic job interview question 顺便说一句,这是一个经典的求职面试问题

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

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