I need create service which will be consume data from long-polling rest service in my backend. When I call this service, backend wait until it has data to send or timeout is expired and send just empty object.
In angular I want service which starts when application is completely loaded, and will be running in background and push data to subjects which I observer.
Can tell me what is the best practice or show me example how to should this service in angular looks like?
Here is my try but it nor call rest on start:
@Injectable()
export class PollingService {
private url: string;
constructor(private http: HttpClient, private fooService: FooService) {
this.url = 'http://localhost:8080/api/poll';
this.startPolling();
}
startPolling() {
this.http.get<any>(this.url)
.map(pollData => {
console.log('poll data', pollData);
this.fooService.mySubject.next(pollData);
if (pollData)
this.startPolling();
});
}
}
The reason you're not getting any data from the service is because you haven't subscribe to it.
A working example could look like this:
startPolling() {
this.http.get<any>('url').subscribe((pollData) => {
console.log('poll data', pollData);
this.fooService.mySubject.next(pollData);
if (pollData)
this.startPolling();
}, (error) => {
console.log(error);
// stop poll or use exponential backoff polling
})
However, HTTP long polling is mediocre nowadays with concepts such as server push, one way to implement them is through web sockets.