1
votes

I tried to follow this example stackblitz and the Observable documentations but it doesn't seem to work for me. Frankly, I'm new to RxJS and don't quite know how to make it work with http and subscribe. Starring at this problem for so long, my brain is mush. Essentially I want subscribe to check for new data every interval. Maybe there is a better way than rxjs?

import { Component, OnDestroy, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Weather } from './interface';
import { Observable } from 'rxjs/Observable';

import { interval } from 'rxjs';
import { take } from 'rxjs/operators';
import { Subject } from 'rxjs';

@Component({
  selector: 'app-weather',
  templateUrl: './weather.component.html',
  styleUrls: ['./weather.component.css']
})
export class WeatherComponent implements  OnInit {
  weathers: any;
  response: any;
  // t = Observable.interval(1000).take(5);
  // numbers = interval(1000);
  // takeFourNumbers = interval(50000).pipe(take(2));


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

          // this.numbers.subscribe(x => console.log('Next: ', x));
        });
    }
}
1
Don't spam the service every second. You will most likely get blocked as a potential DOS attack. Where does the weather change second by second. Polling every ten minutes should be just fine.Adrian Brand
Thank you for reminding the etiquette of not spamming. I'll make a longer interval. Also, I find the solution below to be more precise and elegant than other similar solutions on SO. But if everyone thinks I should delete this question. Please let me know.vt2424253

1 Answers

3
votes

You can use interval to emit every second and then turn each emission into an HTTP request.

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

interval(1000).pipe(
  switchMap(() => this.http.get<Weather>(this.serviceUrl)),
).subscribe(result => {
  // ...
});

You might want to use concatMap instead of switchMap depending on what behavior you want.