我为我的 Angular 应用程序使用了第三方模块的服务。该服务包括一个处理对后端的 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()
几乎同时调用时,它们的结果似乎会相互覆盖 field dataLoaded
。
我怎样才能防止这种行为?是否有一种直接的方法来创建同一服务的多个实例并将其范围限制在一个组件上?
我在 StackOverflow 上找到了一些建议使用自定义工厂函数的答案。这真的是解决这种常见问题的推荐方法吗?
我在Angular 文档中找到了答案。我会把它贴在这里。愿它有一天能帮助某人。
简单的答案是,您必须通过将组件包含在装饰器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 {
// ...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句