Saw your comment on my answer to this. I think it's essentially the same thing (only my examples shows an API being hit every 10 seconds instead of 15 minutes (15*60*1000= 900000).
Some things to take into consideration:
Hard to tell from your code provided what all is going on, but normally, your interaction with an API would be contained in an Angular Service, to encapsulate your interaction with that API. (You should be able to see an example of this in the solution link above.) I would recommend creating a new service to replace your END_USER_SESSION
and INSERT_USER_SESSION
functions.
That Angular service should probably look like:
@Injectable()
export UserSessionService {
constructor(private http: HttpClient) {}
public endUserSession(ip: string): Observable<void> {
// use the HttpClient to hit the API with the given IP
}
public insertUserSession(ip: string): Observable<void> {
// use the HttpClient to hit the API with the given IP
}
}
Then your component code should be something like:
@Component({
//...
})
export class YourComponent implements OnInit, OnDestroy {
private alive: boolean;
private publicIp = require('public-ip');
constructor(private userSessionService: UserSessionService){}
ngOnInit(){
this.alive = true;
TimerObservable.create(0, 900000)
.pipe(
takeWhile(() => this.alive)
)
.subscribe(() => {
this.publicIp.v4().then(ip => {
this.userSessionService.endUserSession(ip).subscribe(() => {
this.userSessionService.insertUserSession(ip).subscribe(() => {
// do nothing
});
});
});
});
}
ngOnDestroy(){
this.alive = false;
}
}
Note the nesting of the insertUserSession
call inside of the subscribe()
of endUserSession
. This will make your insertUserSession
call occur after your endUserSession
call (in your code above, there's a race condition for which of the two will occur first).