我有一个离子2项目,客户通过自定义提供商调用的服务检查剩余单位。目前,客户可以输入参考编号,提供商将像往常一样返回单位,一切正常。我想要的是在后台定期调用此服务,让我们说每30分钟检查一次,以便当单位低于一定值时,我可以通知客户。
GetUnitsProvider:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';
import { Meter } from '../models/meters';
@Injectable()
export class GetUnitsProvider {
constructor(public http: Http) {}
// get the customer units
loadUnitsBalance(id:number): Observable<Meter[]> {
return this.http.get(`http://example.com/balance.pl?referencenumber=${id}&api=json`)
.map(res => <Meter[]>res.json());
}
}
UnitsPage.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Meter } from '../../models/meters';
import { GetUnitsProvider } from '../../providers/get-units-provider';
@Component({
selector: 'units-page',
templateUrl: 'unitspage.html'
})
export class UnitsPage{
reading: Meter[];
clientReferenceNumber:any;
constructor(public navCtrl: NavController,public params:NavParams,private getUnitsProvider: GetUnitsProvider) {
this.clientReferenceNumber = params.get("clientMeterNumber");
getUnitsProvider.loadUnitsBalance(this.clientReferenceNumber).subscribe(reading => {
console.log(reading);
this.reading=reading;
});
}
}
答案 0 :(得分:2)
在您的服务中:
constructor(public http: Http) {
Observable.interval(30 * 60 * 1000)
.switchMap(this.http.get(`...`))
.map(res => res.json())
.subscribe(res => this.check(res))
}
private check(res: <Meter[]>) {
// check whether to notify the user
}
然后在你的模块中使用它(你不需要在任何地方注入服务):
providers: [
{
provide: APP_INITIALIZER,
use: GetUnitsProvider,
deps: [Http],
multi: true
}
],