Observable http service

Viewed 473

I'm 9 hours a day on Angular trying to make some little projects mainly with services. Today, I'm trying to make a service that loops on data's fetching and the components update themselves according to new data. I've like 6 components using the service and the standard way to do it makes 6 times more requests that only one component does.

I heard about IntervalObservable but I don't know how to implement it on the component side. (And maybe I failed in the service too ...)

Here is some code.

app.module.ts :

import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule }    from '@angular/http';

import { AppComponent } from './app.component';


import { ROUTING } from './app.routes';
import {HardwareService} from "./services/hardware.service";
import {AfficheurComponent} from "./components/hardware/afficheur.component";
import {HardwareListComponent} from "./views/hardwarelist/hardwarelist.component";


@NgModule({
    imports: [ BrowserModule, ROUTING, HttpModule, FormsModule],
    declarations: [
        AppComponent,
        AfficheurComponent,
        HardwareListComponent
    ],
    bootstrap: [ AppComponent ],
    providers: [ HardwareService ]
})
export class AppModule { }

hardware.service.ts :

import { Injectable }              from '@angular/core';
import { Headers, Http, Response }          from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/interval'

@Injectable()
export class HardwareService{
    private apiUrl = 'http://10.72.23.11:5000';  // URL to web API

    constructor (private http: Http) {}

    getHardware(){
        return Observable.interval(5000)
            .flatMap(() => {
                return this.http.get(this.apiUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
        });
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || { };
    }
    private handleError (error: Response | any) {
        // In a real-world app, you might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}

afficheur.component.ts :

import { Component } from '@angular/core';
import {HardwareService} from "../../services/hardware.service";

@Component({
    selector: 'afficheur',
    templateUrl: 'app/components/hardware/afficheur.component.html'
})
export class AfficheurComponent{
    public state: Boolean;
    constructor(private service: HardwareService){
        this.service
            .getHardware()
            .subscribe(data => (console.log(data), this.state = data.afficheur),
                error => console.log(error),
                () => console.log('Get etat afficheur complete'))
    }
}

I took the information about IntervalObservable here (SO thread)

As always, I hope you'll be able to help me find my way through this problem :).

ERROR TypeError: Observable_1.Observable.interval is not a function

Regards, Jérémy.

(PS: English is not my mother language, don't hesitate to tell me if i told something you don't understand)

1 Answers
Related