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';
export class SomeOtherComponent implements OnInit {
constructor(private sharedService: SharedService, private someService: SomeService) {}
ngOnInit() {
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)
)
}
}
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