简体   繁体   中英

Angular: Multiple instances of the same service

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?

I found the answer in the Angular docs . I'll post it here. May it help someone someday.

The simple answer is, you have to limit the scope of the service to the component by including it in the provider array of the @Component decorator:

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss'],
  providers: [ ThirdPartyService ]  // <--- this is the solution
})
export class MyComponent {
  // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM