首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从rxjs重构间隔以避免代码重复

如何从rxjs重构间隔以避免代码重复
EN

Stack Overflow用户
提问于 2019-04-10 08:12:16
回答 1查看 109关注 0票数 0

我有以下明显需要改进的代码。使用interval进行重复的http get请求。有没有其他的rxjs方法来改进这段代码?我在interval之外发出第一个http请求的原因是,我首先注意到了interval的延迟,然后使用数据进行响应。因此,第一个请求绕过了延迟。

代码语言:javascript
复制
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Weather } from './interface';
import { Observable } from 'rxjs';
import { concatMap } from 'rxjs/operators';
import { interval } from 'rxjs';
export class WeatherComponent implements  OnInit {
  weathers: any;
  response: any;

  private serviceUrl = 'https://api.weather.gov/gridpoints/OKX/36,38/forecast';
  n = 10000;
  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.response = this.http.get<Weather>(this.serviceUrl );
    this.response.subscribe(
      results => {
        this.weathers = results.properties.periods.slice(0, 2);
      });

    // 5 minute interval
    interval(5 * 60 * 1000).pipe(
      concatMap( () => this.http.get<Weather>(this.serviceUrl) ),
      ).subscribe(results => this.weathers = results.properties.periods.slice(0, 2));
  }

}
EN

回答 1

Stack Overflow用户

发布于 2019-04-10 08:21:34

This answer已经为您的问题提供了答案,但我将保留此答案,因为如果应用不当,它可能会导致其他问题。

重构如下:

代码语言:javascript
复制
import {Subscription, timer} from 'rxjs';

const MILISECS_IN_5_MINS = 5 * 60 * 1000;
export class FooComponent {
    private timerSub = Subscription.EMPTY;

    ...

    ngOnInit() {
      this.timerSub = timer(0, MILISECS_IN_5_MINS).pipe(
        concatMap(() => this.http.get<Weather>(this.serviceUrl))
        ).subscribe(results => this.weathers = results.properties.periods.slice(0, 2));
    }

    ngOnDestroy(){
      // Unsubscribe to avoid mem. leaks, as the timer stream is infinite
      this.timerSub.unsubscribe();
    }

    ...
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55602957

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档