为什么我的Angular/Rxjs6.5 shareReplay(1)不工作?

为什么我的Angular/Rxjs6.5 shareReplay(1)不工作?,angular,typescript,functional-programming,rxjs6,rxjs-observables,Angular,Typescript,Functional Programming,Rxjs6,Rxjs Observables,我的服务类中有非常简单的代码: userContext$ = this.http.post<UserContext>(this.userContextService, {}).pipe( shareReplay(1), tap((val: UserContext) => (this.userContext = val)) ); 第二次: export class PortfolioComponent { userContext$ = this

我的服务类中有非常简单的代码:

userContext$ = this.http.post<UserContext>(this.userContextService, {}).pipe(
    shareReplay(1),
    tap((val: UserContext) => (this.userContext = val))
  );
第二次:

    export class PortfolioComponent {

  userContext$ = this.userContextService.userContext$;
但这似乎不起作用,在我的“网络”选项卡中,我总是有两个呼叫,即使我使用Console.log,也会记录两次:


问题出在我的服务实例上

基本上,userContext是一个单例类(在:root中提供了一个decorator),它直接在PortfolioComponent(PC)内部调用,有些人(PC)也在服务类上,服务类的作用域不是全局的,因此PC将其声明为Provider:[PC服务类]。这迫使cli在每次PC调用userContext时创建一个新的userContext实例

我通过在PC服务类中移动userContext调用解决了这个问题,如下所示:

 providers: [PortfolioService],
})
export class PortfolioComponent {

  welcomeTitle: string = lables.welcomeTitle;
  active = 1;

  userId$ = this.portfolioService.userId$;
  holdingData$ = this.portfolioService.holdingData$;
  userContext$ = this.portfolioService.userContext$;
  userAnnouncements$ = this.portfolioService.userAnnouncements$;
和内部PortfolioService

  userContext$ = this.userContextService.userContext$;
  userAnnouncements$ = this.userContextService.userAnnouncements$;

  constructor(
    private http: HttpClient,
    private userInfoService: UserInfoService,
    private userContextService: UserContextService
  ) {}

感谢@Andrei Gătej花时间和我一起做这件事。

你试过用一个可用的API测试它吗?(接收到200个状态代码)是的,结果相同。在
Observable
xhr.ts
的回调中放置断点后,您是否可以从调试视图添加一张带有调用堆栈的图片?(打开开发工具+(CTRL+P)+
xhr.ts
)。我很确定这样我们就能找出为什么有两个电话。或者更好,看看你是否能把它复制成一个要点,因为它可能包含很多调用。编辑:在其他任何事情之前,服务是在根级别提供的吗?@Andrei在我尝试xhr.ts之前,是的,它是在根级别提供的,我能想到的唯一可疑的事情是,头在核心模块中定义,公文包在应用模块中,应用模块导入核心模块。服务放在应用程序模块中。我不认为这会是一个问题,只要服务是这样提供的
  userContext$ = this.userContextService.userContext$;
  userAnnouncements$ = this.userContextService.userAnnouncements$;

  constructor(
    private http: HttpClient,
    private userInfoService: UserInfoService,
    private userContextService: UserContextService
  ) {}