I am trying to get information from an API and put the data in a HTML Table.
When I load the component, sometimes the table is loading properly and sometimes it stays blank. By checking in the network tab in the debugger, the API responds properly on every request. Also, I don't get any errors in the console.
Here is my service :
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);
}
}
Here is the component that is using this service :
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() {
}
}
However, as you can see above, I tried to add a simple button to the template with a (click) event that does nothing. When I click this button, the table is refreshed and shows the data properly.
I don't know if this issue is linked to angular2 or rxjs.
Thanks for your help.
Httpas shown in your question or do you actually use some other library to fetch the data from thw server?| asyncpipe you could trythis._fishtanksService.getFishtanks().subscribe(value => this.fishtanks = value);