Angular http 服务循环
Angular http service loop
今天我遇到了一个新的服务问题。
我正在尝试创建一个 http 服务,但是当我尝试在我的服务中存储由 http.get.map 返回的 Observable 对象时 - 我的应用程序崩溃了。
我想实现 "system" 服务循环更新数据,订阅可观察对象的组件根据服务数据更新其数据。
代码如下:
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);
}
我如何用我的组件订阅这个?如果我有多个组件,我不知道应该在我的组件中调用什么方法来获取数据而不需要多次调用。
问题是 ngOnInit()
,就像您的 Injectable class 中的那个一样,是 Lifecycle hook which only works with Directives and Components. You should try calling this.loopUpdate()
from within the Injectable class' constructor. You can know more about this on 。
如果要设置获取数据的时间间隔,请在组件 class 中执行,而不是在服务中执行。在服务中,您应该只拥有 return Observables(在您的情况下)调用 http.get()...
的方法。那样的话,您就不会有未定义的对象 returned 和更可重用的服务。
还有,给你看看。
今天我遇到了一个新的服务问题。
我正在尝试创建一个 http 服务,但是当我尝试在我的服务中存储由 http.get.map 返回的 Observable 对象时 - 我的应用程序崩溃了。
我想实现 "system" 服务循环更新数据,订阅可观察对象的组件根据服务数据更新其数据。
代码如下:
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);
}
我如何用我的组件订阅这个?如果我有多个组件,我不知道应该在我的组件中调用什么方法来获取数据而不需要多次调用。
问题是 ngOnInit()
,就像您的 Injectable class 中的那个一样,是 Lifecycle hook which only works with Directives and Components. You should try calling this.loopUpdate()
from within the Injectable class' constructor. You can know more about this on
如果要设置获取数据的时间间隔,请在组件 class 中执行,而不是在服务中执行。在服务中,您应该只拥有 return Observables(在您的情况下)调用 http.get()...
的方法。那样的话,您就不会有未定义的对象 returned 和更可重用的服务。
还有,