2017-03-04 62 views
2

我有一個離子2項目,客戶通過自定義提供商調用的服務檢查剩餘單元。目前,客戶可以輸入參考編號,供應商將照常返回單位,一切正常。我想要的是定期在後臺撥打這項服務,讓我們說每30分鐘一次,並檢查單位,以便當單位低於一定值時,我可以通知客戶。Ionic 2安排服務

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

} 

回答

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 
    } 
], 
+1

嗨,非常感謝,它的工作原理:-) – bobin56

相關問題