下面的代码执行后订阅被调用?

时间:2017-07-07 13:56:06

标签: angular

我有一个看起来像这样的代码 -

ngOnInit(){
          console.log("ngOnInit before service call");
          this._blockCreditCardService.getAccountList().
              subscribe(
                (data)=> {
                          this.accountList=data;
                          console.log("account-list-"+this.accountList[0])
                          console.log(this.accountList.length);
                          if(this.accountList.length>0){
                            this.nonEmptyAccountList=true;
                          }
                          this.options=[];
                          for (let i = 0; i < this.accountList.length; i++) {
                            this.options.push({ value: this.accountList[i], label:this.accountList[i].accountNumber});
                          }
                },
                error=> console.log("Error"),
                ()=> console.info("Completed")
               );
          this.selectedCardFromVerify=[];
          console.log("ngOnInit this.cardDetails-"+this.cardDetails);
          (this.cardDetails) ? this.reSelected(this.cardDetails) : this.isAccountSelected=false;

        }  

,结果是

ngOnInit before service call
capture.component.ts?dfa9:125 ngOnInit this.cardDetails-undefined
core.es5.js?0445:3231 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
capture.component.ts?dfa9:111 account-list-[object Object]  

在浏览器的控制台上。我在这里缺少什么为什么会这样。我是角度2的新手,希望有人在这里发光。谢谢。

1 个答案:

答案 0 :(得分:1)

订阅是异步的,因此当订阅正在等待数据时,服务调用开始并且函数的其余部分继续,然后当数据返回时该线程继续,因此您的ngOnInit控制台日志首先运行,因为该服务没有& #39; t还没有完成数据返回。

如果您希望在数据返回后发生其余指令,则需要在将数据分配给this.accountList = data后将其移动到订阅块中。

ngOnInit(){
          console.log("ngOnInit before service call");
          this._blockCreditCardService.getAccountList().
              subscribe(
                (data)=> {
                          this.accountList=data;
                          console.log("account-list-"+this.accountList[0])
                          console.log(this.accountList.length);
                          if(this.accountList.length>0){
                            this.nonEmptyAccountList=true;
                          }
                          this.options=[];
                          for (let i = 0; i < this.accountList.length; i++) {
                            this.options.push({ value: this.accountList[i], label:this.accountList[i].accountNumber});
                          }
                          this.selectedCardFromVerify=[];
                          console.log("ngOnInit this.cardDetails-"+this.cardDetails);
                          (this.cardDetails) ? this.reSelected(this.cardDetails) : this.isAccountSelected=false;

                },
                error=> console.log("Error"),
                ()=> console.info("Completed")
               );

        }