gpt4 book ai didi

javascript - Angular http 服务循环

转载 作者:行者123 更新时间:2023-12-01 03:37:47 25 4
gpt4 key购买 nike

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

我正在尝试创建一个 http 服务,但是当我尝试在我的服务中存储 http.get.map 返回的 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'))
}
}

硬件.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);
}

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

最佳答案

问题在于 ngOnInit() 与您的 Injectable 类中的一样,是一个 Lifecycle hook它仅适用于指令组件。您应该尝试从 Injectable 类的构造函数中调用 this.loopUpdate()。您可以通过another thread/question了解更多相关信息.

如果要设置获取数据的时间间隔,请在组件类中设置,而不是在服务中设置。在服务中,您应该只具有通过调用 http.get()... 返回 Observables (在您的情况下)的方法。这样您就不会返回 undefined object 和更可重用的服务。

此外,here's another SO link供您查看。

关于javascript - Angular http 服务循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44139825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com