In my Angular 4 app, I have a setup like this (for illustration purposes, I've omitted some code)
@Injectable()
export class SomeService {
constructor(
private http: Http
) {
}
get(id: number) {
return this.http.get('http://somedomain/somemodel/${id}.json');
}
}
This service is utilized by various components to make API calls.
constructor(private someService: SomeService) {}
...
someMethod() {
// code here...
this.someService.get(2).subscribe( someHandlerFunction );
}
someOtherMethod() {
// more code here...
this.someService.get(2).subscribe( someHandlerFunction );
}
The issue at hand is uncertainty around the timing of when someMethod() and someOtherMethod() will be triggered. Sometimes both may be initiated, resulting in two API calls. My aim is to find a way to modify the Service so that the request is only made after a specified timeframe. I attempted to use debounce:
get(id: number) {
return this.http.get(`http://somedomain/somemodel/${id}.json`).debounceTime(10000);
}
I expected that with this approach, the HTTP get request would only occur once every 10 seconds. If a new request is sent within this interval, it would not trigger another call but rather emit the latest value from the observable. However, this method didn't provide the desired outcome. Any suggestions?
PS: While I understand that utilizing a flag could help manage this, it proves to be inefficient as my application has multiple services handling numerous HTTP requests.
Your thoughts on this?