我为我的Angular应用程序使用了service的第三方模块。该服务包括method,用于处理对后端的REST调用。
该服务在Angular应用程序的两个不同组件中使用。但是,有可能两个组件几乎同时发送请求,并且由于REST调用是异步的,因此结果混合起来。
为了更加清楚,这是第三方服务的简化版本:
@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);
}
}
当我的两个组件几乎同时调用callBackend()
时,似乎它们的结果将互相覆盖字段dataLoaded
。
如何防止这种行为?是否有一种直接的方法来创建同一服务的多个实例并将它们的范围限制在一个组件上?
我在StackOverflow上发现了一些answers,建议使用自定义工厂函数。这真的是解决此类常见问题的推荐方法吗?
答案 0 :(得分:0)
在撰写此问题的最后,我在Angular docs中找到了答案。无论如何,我都会在这里发布。希望有一天能对某人有所帮助。
简单的答案是,您必须通过将服务包含在provider
装饰器的@Component
数组中来将服务范围限制为组件:
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss'],
providers: [ ThirdPartyService ] // <--- this is the solution
})
export class MyComponent {
// ...
}