Reputation: 1104
I have very simple code in my service class:
userContext$ = this.http.post<UserContext>(this.userContextService, {}).pipe(
shareReplay(1),
tap((val: UserContext) => (this.userContext = val))
);
This is called twice, first in Header and then in Body:
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HeaderComponent{
userContext$ = this.userContextService.userContext$;
2nd time:
export class PortfolioComponent {
userContext$ = this.userContextService.userContext$;
But this doesn't seems to work, in my Network Tab I always have 2 calls, even if I do Console.log it's logged twice:
Upvotes: 1
Views: 1719
Reputation: 1104
The problem was with the instance of my services.
Basically userContext is a singleton class (with a decorator to providedIn: root) and it was called inside PortfolioComponent (PC) directly, somewhow (PC) has it's on service class also which is not scoped globally hence PC had it’s declared as Provider: [PC Service class]. this was forcing cli to create a new instance of userContext every time PC called it.
I solved it by moved the userContext calls in PC service class, like this:
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$;
And inside PortfolioService
userContext$ = this.userContextService.userContext$;
userAnnouncements$ = this.userContextService.userAnnouncements$;
constructor(
private http: HttpClient,
private userInfoService: UserInfoService,
private userContextService: UserContextService
) {}
Thanks to @Andrei Gătej for spending time with me on this.
Upvotes: 2