sameh
sameh

Reputation: 127

how to refresh data every 5 second using observable

I am quite new to angular2 and rxjs. I am trying to create an angular2 app that gets some data from jsonAPI,

i want to get data every 5 second, i found a solution with Observable.interval(5000) but i have some error while compiling,

how to insert Observable.interval(500) in ngOnInit() code

please!!

   import { Component, OnInit }  from '@angular/core';

import { IProduct } from './product';
import { ProductService } from './product.service';

@Component({
    templateUrl: 'app/products/product-list.component.html',
    styleUrls: ['app/products/product-list.component.css']
})
export class ProductListComponent implements OnInit {
    pageTitle: string = 'Product List';
    imageWidth: number = 50;
    imageMargin: number = 2;
    showImage: boolean = false;
    listFilter: string;
    errorMessage: string;

    products: IProduct[];

    constructor(private _productService: ProductService) {

    }

    toggleImage(): void {
        this.showImage = !this.showImage;
    }

    ngOnInit(): void {
        this._productService.getProducts()
                .subscribe(products => this.products = products,
                           error => this.errorMessage = <any>error);
    }

    onRatingClicked(message: string): void {
        this.pageTitle = 'Product List: ' + message;
    }
}

productservice.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

import { IProduct } from './product';

@Injectable()
export class ProductService {
    private _productUrl = 'api/products/products.json';

    constructor(private _http: Http) { }

    getProducts(): Observable<IProduct[]> {
        return this._http.get(this._productUrl)
            .map((response: Response) => <IProduct[]> response.json())
            .do(data => console.log('All: ' +  JSON.stringify(data)))
            .catch(this.handleError);
    }

    getProduct(id: number): Observable<IProduct> {
        return this.getProducts()
            .map((products: IProduct[]) => products.find(p => p.productId === id));
    }

    private handleError(error: Response) {
        // in a real world app, we may send the server to some remote logging infrastructure
        // instead of just logging it to the console
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

Upvotes: 2

Views: 9759

Answers (2)

Hamed Baatour
Hamed Baatour

Reputation: 6942

make sure your service look like this and you don't miss any imports:

import 'rxjs/Rx';
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

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

      getData() {
        return Observable.interval(5000).flatMap(() => {
          return this._http.get(`URL GOES HERE`)
            .map(res => res.json());
        });
      }
    }

and in your component:

import { Component, OnInit }  from '@angular/core';
import { ProductService } from './product.service';

export class ProductListComponent implements OnInit {
    constructor(public _productService: ProductService) {}

 ngOnInit() {
    this._productService.getData()
      .subscribe(data => this.products = data,
               err => console.log(err));
  }
}

This should work but make sure that you share any errors that you get in the console as your question is missing that.

Upvotes: 2

Sajeetharan
Sajeetharan

Reputation: 222682

You need to modify inside your ProductService.ts as follows,

 getProducts(){
    Observable.interval(5000)
      .flatMap(() => this.http.get(URL)
      .map( res => res.json() )
      .catch( (error:any) => Observable.throw(error.json().error || 'Server error') ) )
      .subscribe(data => {
         console.log(data)
      })
}

Upvotes: 3

Related Questions