角度6:如何间隔获取http

时间:2019-03-20 02:04:18

标签: angular observable angular-http angular-httpclient

我似乎无法使用此solution来处理我的代码。 这是我的原始代码,没有间隔。但不幸的是,它发出了太多请求。

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

constructor(private http: HttpClient) {}
  ngOnInit() {
  }
  getWeather() {
    this.response = this.http.get<Weather>(this.serviceUrl );
    this.response.subscribe(
      results => {
        this.weathers = results.properties.periods;
        console.log('this.weather ====> ', this.weathers);
      });
    }
}

但是现在添加间隔时出现错误:

  

错误TypeError:无法读取未定义的属性“间隔”

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

constructor(private http: HttpClient) {}
  ngOnInit() {
  }
  getWeather() {
    this.response = this.http.get<Weather>(this.serviceUrl );
    this.response.Observable.interval(60000).subscribe(
      results => {
        this.weathers = results.properties.periods;
        console.log('this.weather ====> ', this.weathers);
      });
    }
}

我使用了以下代码,该代码不会给我任何错误,但是它仍然会无限响应,好像间隔没有影响。

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { interval } from 'rxjs';
import { take } from 'rxjs/operators';
import { Subject } from 'rxjs';
takeFourNumbers = interval(50000).pipe(take(4));
constructor(private http: HttpClient) {}
  ngOnInit() {
  }
  getWeather() {
    this.response = this.http.get<Weather>(this.serviceUrl );
    this.response.subscribe(
      results => {
        this.weathers = results.properties.periods;
        console.log('this.weather ====> ', this.weathers);
        this.takeFourNumbers.subscribe(x => console.log('Next: ', x));
      });
    }
}

Angular 6+最近没有改变,旧的解决方案不再起作用了吗?我是Angular的新手。

1 个答案:

答案 0 :(得分:1)

尝试如下:

import { interval } from 'rxjs';
import { map } from 'rxjs/operators'

interval(50000).pipe(
  map((x) => { /* your code here */ })
);