简体   繁体   English

如何在Angular 2 Http可观察请求上设置一个整数

[英]How to Set an Inteval on Angular 2 Http Observable Request

I made an Angular 2 service that successfully gets data from my server. 我做了一个Angular 2服务,该服务成功地从服务器获取了数据。 It has one function named getSinglePowerBlock . 它具有一个名为getSinglePowerBlock函数。 The goal of this function is to setup an observable to make the get request to the given URL, and return one of the powerblock elements from the JSON property assets.powerblock[] . 该函数的目标是设置一个可观察的对象,以使get请求到达给定的URL,并从JSON属性assets.powerblock[]返回powerblock元素之一。 I know this works successfully, because I can get it to work in one of my components. 我知道这可以成功完成,因为我可以在我的一个组件中使用它。 I have included that component, for reference. 我已包含该组件,以供参考。

My Goal: I want my code to make the get call continuously, once per second, using the interval function from the rxjs library. 我的目标:我希望我的代码使用rxjs库中的interval函数连续每秒一次进行get调用。 Then, I want my local data to update with the data from each poll response. 然后,我希望我的本地数据用每个轮询响应中的数据进行更新。 Basically, a polling solution. 基本上是一种轮询解决方案。

I imagine it's not hard to do, but I'm new to Observables and Rxjs and I just can't seem to get the syntax correct. 我想这并不难,但是我是Observables和Rxjs的新手,而且我似乎无法正确理解语法。 Feel free to offer a better way to do the getPowerBlock function or the way I'm calling it. 请随意提供一种更好的方法来执行getPowerBlock函数或我调用它的方法。 I'm sure you're much smarter than me at this. 我敢肯定,你在这方面比我聪明得多。

I only want the polling to be on when this component is the current page being viewed by the user. 我只希望在该组件是用户正在查看的当前页面时打开轮询。

The Service: 服务:

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable }     from 'rxjs';
import 'rxjs/Rx';

import { PowerBlock } from './classes/power-block';

@Injectable()
export class ServerCommsService {

  private pbIndex: number = 0;

  constructor (private http: Http) {}

  getPowerBlock(): Observable<PowerBlock> {
    return this.http
      .get('/database-calls/getdata?type=powerblock')
      .map((r: Response) => r.json().assets.powerblock[this.pbIndex] as PowerBlock);
  }
}

The Component that uses the Service: 使用服务的组件:

import { Component, OnInit } from '@angular/core';
import { Observable }        from 'rxjs/Observable';

import { PowerBlock } from '../classes/power-block';
import { ServerCommsService } from '../server-comms.service';

@Component({
  moduleId: module.id,
  selector: 'power-block',
  templateUrl: 'power-block.component.html'
})
export class PowerBlockComponent implements OnInit {
  public title: string = 'PowerBlock';
  private powerBlock: PowerBlock;

  constructor(
    private server: ServerCommsService
  ) {}

  ngOnInit(): void {
    this.server.getPowerBlock().subscribe(
      pb => this.powerBlock = pb,
      err => {console.log(err)}
    );
  }
}

The JSON returned from the server: 从服务器返回的JSON

{
    "assets": {
        "powerblock": [
            {
                "id": "001",
                "name": "PB1",
            },
            {
                "id": "002",
                "name": "PB2",
            }
        ]
    }
}

I don't think so its wise to call an interval on a returned promise/observable but if you are just returning the data (not observable/promise), you can do this inside the timer in angular2. 我认为在返回的promise / observable上调用一个间隔不是很明智,但是如果您只是返回数据(不是observable / promise),则可以在angular2的计时器中执行此操作。 It will continuously call the function after 1 second 1秒后将连续调用该函数

import {OnInit, OnDestroy} from '@angular/core';

Create a subscription holder variable in your component 在您的组件中创建订阅持有人变量

private timerSubscription: any;   //just to hold the reference

You can initialize the timer in your OnInit event and get the subscription back in your variable in order to unsubscribe later in OnDestroy. 您可以在OnInit事件中初始化计时器,并在变量中重新获得订阅,以便稍后在OnDestroy中取消订阅。

ngOnInit()
{
    //start a timer after one second
    let timer = Observable.timer(1000, 1000);
    this.timerSubscription = timer.subscribe((t:any) => {
        //call your getPowerBlock function here 
    });
}

In last, just destroy the subscription as its no longer needed. 最后,销毁不再需要的订阅。

ngOnDestroy()
{
    if(this.timerSubscription)
        this.timerSubscription.unsubscribe();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM