Having trouble polling data with a GET request from the API. I want to poll data every 1 second for up to 30 seconds. The issue is, angular appears to be sending requests (logging responses), but doesn't actually send a request to the server.
Here are the methods I wrote in my service:
private pollStatus(token: string, remember: boolean):Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
'Token': token,
'Remember': '' + remember
})
};
const url = 'auth/status';
return this.http.get<any>(url, httpOptions).pipe(map(response => {
console.log('polldata', response.status);
return response;
}));
}
public secondFactor(token: string, remember: boolean): Observable<any> {
let pollData$ = this.pollStatus(token, remember);
let watchdog = timer(30 * 1000);
// this.http.post<any>('/auth/login', {}).subscribe();
return Observable.create(subject => {
let pollSubscription = pollData$.pipe(expand(_ => timer(1000).pipe(concatMap(_ => pollData$))), takeUntil(watchdog)).subscribe(response => {
console.log('secondFactor', response.status);
// some action based on the response is performed here
});
});
}
Calling the component like this:
public ngOnInit(): void {
this.authService.secondFactor(this.authyToken, true).subscribe(response => {
console.log('response in component', response);
});
}
In the console, I see that the GET request subscription is happening multiple times (code:
console.log('polldata', response.status);
is executed). However, only one request is actually made to the server (confirmed on the back-end and in the network tab).
Console output:
polldata pending
secondFactor pending
polldata pending
secondFactor pending
polldata pending
secondFactor pending
polldata pending
secondFactor pending
polldata pending
secondFactor pending
etc. etc. etc.
Tested this behavior on different browsers (Safari & Chrome) - same issue.
Work-around:
Discovered that if I send a POST request to the server (commented line:
// this.http.post<any>('/auth/login', {}).subscribe();
in the secondFactor()
method), then Angular starts performing GET requests more than once.