Reputation: 119
I get data from remote server. CORS is configured. I use interval() operator form RXJS library.
Component:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/switchMap';
private getUserTasks(userId): void {
Observable
.interval(5000)
.switchMap(() => this.tasksService.getUserTasks(userId))
.subscribe(
data => {
this.userTasks = JSON.parse(data);
console.log('userTasks', this.userTasks);
}
)
};
Service return observable object:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TasksService {
constructor(private http: HttpClient) { };
getUserTasks(userId): Observable<any> {
return this.http.get('http://blabla.com/app_tasks/user_tasks?user_id=' + userId);
};
}
But after the user enters the page, he waits 5 seconds (and looks at the white screen). I need to send a request immediately after the page is loaded. And then every 5 seconds the request was repeated
Upvotes: 0
Views: 166
Reputation: 13396
You can use startWith to have the sequence emit an initial value
private getUserTasks(userId): void {
Observable
.interval(5000)
.startWith(0)
.switchMap(() => this.tasksService.getUserTasks(userId))
.subscribe(data => {
this.userTasks = JSON.parse(data);
console.log('userTasks', this.userTasks);
})
};
Upvotes: 2