Angular http服务循环

时间:2017-05-23 16:02:44

标签: javascript angular typescript angular-services angular-http

今天我面临服务的新问题。

我正在尝试创建一个http服务,但当我尝试在我的服务中存储http.get.map返回的Observable对象时 - 我的应用程序崩溃了。

我想实现一个“系统”,服务循环更新数据,订阅observable的组件根据服务的数据更新其数据。

以下是代码:

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'))
    }
}

hardware.service.ts:

import { Injectable, OnInit }              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';

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

    private ressources: Observable<any>;

    constructor (private http: Http) {}

    ngOnInit() {
        this.loopupdate()
    }

    loopupdate(): void {
        setInterval(() => {
            this.update();
        }, 5000);
    }

    update(): void {
        this.ressources = this.http.get(this.apiUrl)
            .map(this.extractData)
            .catch(this.handleError);
    }

    getHardware(){
        return this.ressources;
    }

    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);
    }
}

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, HttpModule],
        declarations: [
            AppComponent,
            AfficheurComponent,
            HardwareListComponent
        ],
        bootstrap: [ AppComponent ],
        providers: [ HardwareService ]
    })

export class AppModule { }

再次感谢您的光临:D

编辑:

我尝试启动应用时遇到错误:

ERROR TypeError: Cannot read property 'subscribe' of undefined

我认为它与this.ressources初始化有关,任何想法?

编辑2: 在我的服务中:

initializePolling(){
        return IntervalObservable.create(5000)
            .flatMap(() => {
                return this.getHardware()
        });
    }

getHardware(): Observable<any> {
        return this.http.get(this.apiUrl)
            .map(this.extractData)
            .catch(this.handleError);
    }

我如何使用我的组件订阅此内容?如果我有多个组件,我不知道在我的组件中应该调用哪种方法来获取数据而不进行多次调用。

1 个答案:

答案 0 :(得分:1)

问题是,ngOnInit()与您的可注入类中的this.loopUpdate()一样,Lifecycle hook仅适用于指令部件即可。您应该尝试在可注入类中调用http.get()...&#39; 构造即可。您可以在another thread/question上了解详情。

如果要在获取数据时设置间隔,请在组件类中执行此操作,而不是在服务中执行。在服务中,您应该只有方法可以通过调用numpy.array返回 Observables (在您的情况下)。通过这种方式,您将不会返回未定义的对象和更可重用的服务。

另外,here's another SO link让你看看。