2016-09-26 32 views
1

在我的模板我有一個按鈕來觸發下面的方法:Angular2需要點擊兩次來檢索JSON並生成HTML

getResults() { 
     this.resultService.getResultsAsTree(this.disk1.id, this.disk2.id, this.mode) 
      .subscribe(
       results => this.json = results, 
       error => this.errorMessage = <any>error); 

     this.getHTML(); 
    } 

的方法贊同其檢索JSON對象服務,這樣可以節省成this.json屬性。 緊接着就會調用this.getHTML()功能應通過遞歸方法JSON格式轉換成HTML樹視圖:

getHTML() { 
     this.html = ''; 
     this.html += '<div class=\"jstree\"><ul>'; 
     this.structureAsTree(this.json); 
     this.html += '</ul></div>'; 
    } 



    structureAsTree(obj: Object) { 
     for (var key in obj) { 
      if (!this.isEmpty(obj[key])) { 
       this.html += '<li>' + key + '<ul>'; 
       this.structureAsTree(obj[key]); 
       this.html += '</ul></li>'; 
      } else { 
       this.html += '<li>' + key + '</li>'; 
      } 
     } 

    } 

問題

不幸的是,我必須按一下按鈕兩次,以顯示呈現的HTML。但是,從控制檯我已經看到第一次點擊檢索了JSON對象。

我認爲xhr調用是異步的,所以當創建HTML時this.json是空的。

任何提示如何解決這個問題,所以數據顯示在第一次點擊?

感謝。

您的問題

回答

2

解決方案:

() =>代碼後
getResults() { 
    this.resultService.getResultsAsTree(this.disk1.id, this.disk2.id, this.mode) 
     .subscribe(
      results => this.json = results, // what to do with result 
      error => this.errorMessage = <any>error), // what to do if you get error 
      () => this.getHTML(); // what to do after you get the result 
} 

你從http請求數據後執行。 Http請求是異步操作,這就是爲什麼在第一次點擊時無法用當前代碼生成HTML的原因 - 在請求完成之前調用this.getHTML()

+1

工作,但我應用JQuery插件Jstree沒有得到應用,並沒有渲染數據作爲一個樹了。標記此源問題已解決。謝謝。 – nehemia