2017-07-07 27 views
-1

我有一個看起來像這樣的代碼 -訂閱以下代碼執行後調用?

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,並希望有人在這裏擺脫一些光。謝謝。

+0

你明白異步功能的概念嗎? –

+0

您的服務發出AJAX請求。 AJAX中的A表示**異步**。訂閱和傳遞迴調的關鍵點是......稍後回覆,當回覆可用時。就像當你吃早餐時,你要烤麪包,然後看報紙,然後當烤麪包機發出叮叮聲,告訴你「你的麪包已經準備好了」時,纔開始吃烤麪包。如果服務調用是同步的,它將不會返回可觀察對象。它會直接返回結果。 –

回答

1

訂閱是異步的,因此服務調用將開始,並且在訂閱正在等待數據時繼續執行其餘的功能,然後該線程在數據恢復時繼續,因此您的ngOnInit控制檯日誌首先運行,因爲服務尚未完成返回數據。

如果您希望在數據恢復後執行其餘指令,則需要在將數據分配給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") 
       ); 

     } 
+0

雖然我爲自己的問題得到了很多低估,但至少我得到了答案。謝謝。我不僅對角度很陌生,而且對UI也是新手。 – basari66

+0

取而代之,尋求幫助並得到否定的回答可能會令人沮喪。不要讓它讓你失望,只要嘗試提出清晰簡潔的問題,並提供儘可能多的證據,以便在轉向StackOverflow之前先嚐試自己解決問題,並且你應該沒問題。我很高興能夠提供幫助。如果我的回答是最好的,如果你可以將其標記爲這樣,將不勝感激。乾杯! –