2016-03-27 78 views
0

我想從API獲取信息並將數據放入HTML表中。Angular 2異步管道不刷新

當我加載組件時,有時表正在加載正確,有時它保持空白。通過檢查調試器中的網絡選項卡,API可以對每個請求做出正確響應。另外,我不會在控制檯中發現任何錯誤。

這裏是我的服務:

import 'rxjs/Rx'; 
import {Injectable} from 'angular2/core'; 
import {Http, Response} from 'angular2/http'; 

import { Fishtank } from './fishtank'; 

@Injectable() 
export class FishtanksService { 
    constructor(private _http: Http) { 
    } 

    getFishtanks() { 
     var response = this._http.get("http://localhost:10239/api/fishtank"); 
     return response.map((response: Response) => <Fishtank[]>response.json().fishtanks); 
    } 
} 

下面是使用此服務的組件:

import {Component, OnInit} from 'angular2/core'; 
import { Observable } from 'rxjs/Rx'; 

import {Fishtank} from './fishtank'; 
import {FishtanksService} from './fishtanks.service'; 

@Component({ 
    selector: 'fishtanks', 
    templateUrl: `<div> 
        <table class="table table-striped table-condensed"> 
         <thead> 
          <tr> 
           <th>id </th> 
           <th> batchNumber </th> 
           <th> userGroup </th> 
          </tr> 
         </thead> 
         <tbody > 
          <tr *ngFor="#fishtank of fishtanks | async"> 
           <td>{{fishtank.id }}</td> 
           <td> {{fishtank.batchNumber }}</td> 
           <td> {{fishtank.userGroup }}</td> 
          </tr> 
         </tbody> 
        </table> 
       </div> 
       <button (click)="click()">Click me</button>` 
}) 

export class FishtanksComponent implements OnInit { 
    constructor(private _fishtanksService: FishtanksService) { 
    } 

    public fishtanks: Observable<Fishtank[]>; 

    public getFishtanks() { 
     this.fishtanks = this._fishtanksService.getFishtanks(); 
    } 

    ngOnInit() { 
     this.getFishtanks() 
    } 
    public click() { 
    } 
} 

然而,正如你可以在上面看到,我想一個簡單的按鈕添加到帶有(單擊)事件的模板,它不做任何事情。當我點擊這個按鈕時,表格被刷新並正確顯示數據。

我不知道這個問題是否與angular2或rxjs鏈接。

感謝您的幫助。

+0

不知怎的角沒有得到通知的一些事件來做到這一點的變化檢測。你使用'Http'如你的問題所示,或者你真的使用其他庫來從thw服務器獲取數據嗎? –

+0

而不是使用'| async' pipe你可以試試'this._fishtanksService.getFishtanks()。subscribe(value => this.fishtanks = value);' –

+0

我使用Http,如圖所示,我會嘗試訂閱。 – Kilop

回答

2

我通過重新安排index.html中的引用來解決問題。

這裏,使得它不能正常工作秩序:

<script src="libs/angular2-polyfills.js"></script> 
<script src="libs/es6-shim.min.js"></script> 
<script src="libs/system-polyfills.js"></script> 
<script src="libs/shims_for_IE.js"></script> 
<script src="libs/system.js"></script> 
<script src="libs/rx.js"></script> 
<script src="libs/angular2.dev.js"></script> 
<script src="libs/router.dev.js"></script> 
<script src="libs/http.dev.js"></script> 

這裏是固定它的順序:

<script src="libs/es6-shim.min.js"></script> 
<script src="libs/system-polyfills.js"></script> 
<script src="libs/shims_for_ie.js"></script> 
<script src="libs/angular2-polyfills.js"></script> 
<script src="libs/system.js"></script> 
<script src="libs/rx.js"></script> 
<script src="libs/angular2.dev.js"></script> 
<script src="libs/router.dev.js"></script> 
<script src="libs/http.dev.js"></script>