Angular Real Time Data
First of all, I am very new to Angular and I am struggling to figure it out. I made an application that I want to receive in real time from a webserver that sends JSON data from an mssql server.
I managed to get the data like this:
export class AppComponent {
posts:string;
constructor(http: Http) {
http.get('https://jsonplaceholder.typicode.com/posts')
.map(res => res.json())
.subscribe(data => this.posts = data);
}
}
and then just paste it into my html document like so <h1>{{data.id}}</h1>
But when my web server refreshes the JSON the html is not refreshed at all. I understand that I am missing something substantial as an observable and I would appreciate it if someone can nudge me in the right direction.
source to share
If you want to constantly ask the server for the latest data, you need to call the server at intervals:
import { Observable } from 'rxjs';
export class AppComponent {
posts:string;
ngOnInit() {
this.posts = Observable
.interval(1000) // call once per second
.startWith(0)
.switchMap(() =>
this.http.get('https://jsonplaceholder.typicode.com/posts')
.map((res: Response) => res.json());
})
// example how to get just the first result
.map(posts => posts[0]);
}
Then, in the template, use an async pipe:
<pre>{{ (posts | async) | json }}</pre>
source to share
You should move this http call to a service after all, but for learning purposes, you can move it to a method that ngOnInit is called when the component is initialized. Since you want to receive data continuously, use the interval for the observable.
It may not be perfect / accurate code that you can copy / paste, but it should give you some ideas.
import { Component, OnInit } from '@angular/core';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
//import Angular Http or custom Http
//(Your decorators/class declaration here)
posts$: Observable<yourType[]>
constructor(http: Http) { }
ngOnInit(){
this.getData();
}
getData(): void {
this.posts$ = Observable.interval(1000)
.startsWith(0)
.switchMap(() =>
this.http.get('https://jsonplaceholder.typicode.com/posts')
.map(res => res.json());
)
}
Then use an async pipe and a * ngFor loop in your template:
<div *ngFor="let post of (posts$ | async)">
<h1>{{post?.id}}</h1>
</div>
source to share