我试图从API获取信息并将数据放在HTML表中 .
当我加载组件时,有时表正在正确加载,有时它会保持空白 . 通过检入调试器中的网络选项卡,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有关 .
谢谢你的帮助 .
1 回答
我通过重新安排index.html中的引用来解决问题 .
这是使它不起作用的顺序:
这是修复它的顺序: