The Issue
In my Angular application, I am using a third-party module service that handles REST calls to the backend. This service is utilized in two separate components, but conflicts can arise when both components make requests simultaneously due to the asynchronous nature of the REST calls.
To illustrate, here is a simplified version of the third party service:
@Injectable({
providedIn: 'root'
})
export class ThirdPartyService {
dataLoaded: Subject<Result> = new Subject();
callBackend(request: RequestBody): Observable<Result> {
const promise = this.someJSLibrary.call(request);
promise.then((result: Result) => {
this.dataLoaded.next(result);
});
return from(promise);
}
}
When both components call callBackend()
at the same time, their results may overwrite each other in the dataLoaded
field.
The Query
How can this conflicting behavior be prevented? Is there a way to create multiple instances of the service and restrict their scope to individual components?
I have come across suggestions on StackOverflow recommending the use of custom factory functions to address this issue. Is this the most effective solution for tackling such a common problem?