I am working on an angular v14 application and I am having trouble figuring out how to fix an issue with my component making duplicate api calls.
I have a service that is shared between all components to set and retrieve state values. The value needed for the api call has an initial value set to be able to make the request when the component initializes.
@Injectable()
export class SharedService {
private type$ = new BehaviorSubject<string>('some-tab-value');
setType(type: string) {
this.type$.next(libraryType);
}
getType() {
return this.type$.asObservable();
}
}
I have a top level component that sets the BehaviorSubject value whenever a user clicks a tab on the page with the tab value;
import { SharedService } from './services/shared.service';
export class TopLevelComponent {
private initialValue = 'some value';
constructor(private sharedService: SharedService) {}
onTabClick(type) {
this.sharedService.setType(type);
}
}
I have another component that subscribes to the tab value clicked in the top level component. It is needed to make an api call.
import { SharedService} from '../../services/shared.service';
import { SomeService } from './services/some.service';
import { Subscription } from 'rxjs';
export class SomeOtherComponent implements OnInit, OnDestroy {
subscriptionList: Subscription = new Subscription();
constructor(
private sharedService: SharedService,
private someService: SomeService
) {}
ngOnInit() {
this.subscriptionList.add(
this.sharedService.getType().pipe(
switchMap(selectedType => {
// some api call
return this.someService.getStuff(selectedType)
})
).subscribe(value => {
// this value is always logging twice when the component loads
// also logs twice when clicking on tab in UI
console.log(value)
)
);
}
ngOnDestroy() {
this.subscriptionList.unsubscribe();
}
}
The service that is handling the http requests look something like this
import { HttpClient } from '@angular/common/http';
@Injectable()
export class SomeService {
constructor(private httpClient: HttpClient) {}
getStuff(type) {
return this.httpClient.get('some-url').pipe(
catchError(err => {
return throwError(() => new Error('Error while fetching stuff: ' + err));
}
)
}
}
I think it has to do with the BehaviorSubject emitting the last and current values. I tried switching the BehaviorSubject into a Subject instead. However, since a Subject doesn’t take an initial value, I tried to set the initial value in the ngOnInit function inside the top level component. The other component does not fire the http request until the user clicks on a tab (but i want it to also fire when initializing).
I feel like this should be an easy fix but I have been stuck trying to resolve this. Any help is appreciated. Thanks
2
Answers
When the component is destroyed make sure you unsubscribe the subscription to the BehaviourSubject, else it will continue to live and cause memory leaks, even if the component is destroyed.
The reason you are getting two console outputs is because the
BehaviourSubject
you are observing is emitting it’s value twice. Once when you are subscribed and once when you call your setType function. That is howBehaviourSubject
works. Check out https://rxjs.dev/api/index/class/BehaviorSubjectFor your use case, you could opt for a normal
Subject
which will emit a value once on change and have a default tab selected in the UI. What is the reason you need to emit an initial value as soon as you subscribe?