The Problem
I use a service of a third-party module for my Angular application. This service includes a method that handles the REST-calls to the backend.
The service is used in two different components of my Angular application. However, it can happen that both components send a request nearly at the same time and - since the REST-calls are asynchronous - the results get mixed up.
To make it more clear, 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 of my components call callBackend()
nearly at the same time, it seems as if their results would overwrite each other the field dataLoaded
.
The Question
How can I prevent this behavior? Is there a straightforward way to create multiple instances of the same service and limit their scope on one component?
I found some answers on StackOverflow that recommend using a custom factory function. Is this really the recommended way of solving such a common problem?