Search code examples
angularangular2-observablesngoninit

Angular 4 Poll / Stream Data from service within ngOnInit


I would like to use AngularJS 4 to stream data from an API. When I first call the API there is no data, but eventually more results will be returned over a 15 - 30 second period.

Here is my component:

export class ResultsComponent implements OnInit {
    results: Results;

    constructor(
        private searchService: SearchService,
        private route: ActivatedRoute
    ) {}

    ngOnInit(): void {

        this.route.params
            .switchMap((params: Params) => 
        this.searchService.getResultsObservable(params['searchKey']))
            .subscribe(data => { this.results = data; });
}

Here are my service calls:

I'm using the Observable call above, but I've included the Promise call as well.

getResults(searchKey: string): Promise<Results> {
    const url = `${this.apiUrl}/${searchKey}/0`;
    return this.http.get(url)
            .toPromise()
            .then(response => response.json() || {})
            .catch(this.handleError);
}

getResultsObservable(searchKey: string): Observable<Results> {
    const url = `${this.apiUrl}/${searchKey}/0`;
    return this.http
            .get(url)
            .map(response => response.json() || {});
}

I believe I need to use the Observable call, but I'm not sure how I need to handle the call within the component.


Solution

  • Thanks, @mridula for getting me on the right track. After some research, I see the best solution is to use an IntervalObservable:

    subscription: Subscription;
    
    ngOnInit() {
        this.route.params.subscribe(
          (params: Params) => {
            this.subscription = this.getResults((params['searchKey'])).subscribe(
              (response) => {
                console.log(response);
                //your business logic for each loop
                //once your are done
                this.stopInterval();
            }
          }
        );
      }
    );
    
    getResults(searchKey: string): {
          return IntervalObservable
          .create(1000) //1 second interval
          .flatMap(() => {
          return this.http.get('[API_URL]/' + searchKey).map(response => response.json());
      });
    }
    
    stopInterval(){
        this.subscription.unsubscribe();
    }