Is there a way to continuously poll my API until a value is retrieved (but stop when it fails)? Right now, it makes the call, but as there is nothing there at the time, it does not retry. I want the retries to continue unless the call fails.
Component
ngOnInit(): void {
this.getCurrentUser(this.uid);
}
getCurrentUser(uid: string) {
this.userService.getUser(uid).then((user: IUser[]) => {
if (user && user.length > 0) {
this.user = user[0];
}
});
}
Service
getUser(uid: string): Promise<Object | IUser[]> {
return this.firebaseService.generateToken().then((token: string) => {
return this.httpClient
.get(`${environment.apiBasePath}/users/${uid}`, {
headers: { authorization: `Bearer ${token}` },
})
.toPromise();
});
}
Call the function again from within itself if there is no data being returned.
getCurrentUser(uid: string) {
this.userService.getUser(uid)
.then((user: IUser[]) => {
if (user && user.length > 0) {
this.user = user[0];
} else {
this.getCurrentUser(this.uid)
}
})
.catch(error = console.error(error);
}
Perhaps set a limit on how many times you want this to happen? Or set use a setTimeout
on the recall (in the else clause) so that it doesn't happen too rapidly?