2016-08-17 39 views
2

以下是我正在嘗試基於Angular Tutorial進行工作的內容。直到任何對象被點擊後,角度2纔會更新

export class DashboardComponent implements OnInit { 
     title = 'Current Robots'; 
     private sobots: Robot[]; 

     constructor(
     private router: Router, 
     private sobotService: RobotService) { 
     } 

     getRobots() { 
      this.sobotService.getRobots().then(sobots => Array.prototype.push.apply(this.sobots, sobots.data));  
     } 

     ngOnInit() { 
      this.getRobots(); 
     } 

     gotoDetail(sobot: Robot) { 
     let link = ['/detail', sobot.Id]; 
     this.router.navigate(link); 
     } 

和視圖

<h3>{{title}}</h3> 
<div class="grid grid-pad">   
    <div *ngFor="let sobot of sobots" (click)="gotoDetail(sobot)" class="col-1-4"> 
    <div class="module sobot"> 
     <p>HostKey</p> 
     <h4>{{sobot.HostKey}}</h4> 
    </div> 
    </div> 
</div> 
<sobot-search></sobot-search> 

sobots.data看起來是返回預期的數據對象 - 但它仍然沒有更新,直到我點擊任何按鈕/路由/任何事件。

沒有錯誤在控制檯中顯示出來,我很困惑!

我已經先行一步,並試圖確保它只是將數據添加到原數組對象,但即使這樣似乎並沒有工作!

回答

3

因此,原來的sobotService被返回q.js承諾,而不是一個ES6的承諾。我相信這可能是爲什麼它沒有像我期望的那樣更新它喜歡它在英雄教程中做的。

,迫使它在該區域如更新:

this.sobotService .getRobots().then(ODataRobots => { 
     this.zone.run(() => this.sobots = ODataRobots.data);   
    }); 

它設法儘快解決的承諾更新視圖。

我可能會要弄清楚,如果有一個簡單的方法來去除q.js從我使用(o.js)庫中,但在這部作品中預期同時承諾!

+0

我會擴展這個答案,包括如何利用NgZone。以下文章完美地解釋了它。 https://blog.thoughtram.io/angular/2016/02/01/zones-in-angular-2.html –

1

嘗試分配一個初始值this.sobots。

export class DashboardComponent implements OnInit { 
     title = 'Current Robots'; 
     private sobots: Robot[] = []; <---- this 

     constructor(
     private router: Router, 
     private sobotService: RobotService) { 
     } 

     getRobots() { 
      this.sobotService.getRobots().then(sobots => Array.prototype.push.apply(this.sobots, sobots.data));  
     } 

     ngOnInit() { 
      this.getRobots(); 
     } 

     gotoDetail(sobot: Robot) { 
     let link = ['/detail', sobot.Id]; 
     this.router.navigate(link); 
     } 
} 

否則,你試圖推到一個空對象,我不認爲push.apply會爲此工作。在的NodeJS:

> let x 
undefined 
> x 
undefined 
> Array.prototype.push.apply(x,['y','z']) 
TypeError: Array.prototype.push called on null or undefined 
    at repl:1:22 
    at REPLServer.defaultEval (repl.js:272:27) 
    at bound (domain.js:280:14) 
    at REPLServer.runBound [as eval] (domain.js:293:12) 
    at REPLServer.<anonymous> (repl.js:441:10) 
    at emitOne (events.js:96:13) 
    at REPLServer.emit (events.js:188:7) 
    at REPLServer.Interface._onLine (readline.js:224:10) 
    at REPLServer.Interface._line (readline.js:566:8) 
    at REPLServer.Interface._ttyWrite (readline.js:843:14) 
+0

好點!這是問題的一部分。仍然沒有結束,但它確實幫助我找到問題。乾杯:) – Nathan