Keystone Jack
Keystone Jack

Reputation: 309

Real time data Angular

First of all, I am very new to Angular and I am struggling to get this right. I have made an app that I want to get real time data from a web server that is posting JSON data from an mssql server.

I have managed to retrive data like so

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 insert it to my html document like this <h1>{{data.id}}</h1>

But when my web server updates the JSON, the html does not update at all. I understand that I am missing something essential , like observable and I would be grateful if someone can push me in the right direction.

Upvotes: 3

Views: 3345

Answers (2)

Eeks33
Eeks33

Reputation: 2315

If you want to continuously ask the server for the latest data, you'll need to call the server at an interval:

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 template use async pipe:

<pre>{{ (posts | async) | json }}</pre>

Upvotes: 3

jhhoff02
jhhoff02

Reputation: 1210

You should move that http call into a service eventually, but for learning purposes you can move it into a method that is called by ngOnInit when the component initializes. Since you want to get data continuously, use an interval on the observable.

This might not be the perfect/exact code 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's 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 the async pipe and *ngFor loop in your template:

  <div *ngFor="let post of (posts$ | async)">
     <h1>{{post?.id}}</h1>
  </div>

Upvotes: 1

Related Questions