Within my Angular project, I am retrieving data from an API using a service and storing the data within a BehaviorSubject as shown below
private categorySubject = new BehaviorSubject<number | null>(null);
apiBehavior = new ReplaySubject<ApiResponseInterface>();
constructor(private http: HttpClient, private authService: AuthService) {}
getQuestions(page: string = '', category = this.categorySubject.getValue()): Observable<ApiResponseInterface> {
let url = this.baseUrl;
if (category) {
console.log(category);
url = this.baseUrl + '/category/' + category;
}
const params = new HttpParams().set('cursor', page);
return this.http.get<ApiResponseInterface>(url, { params })
.pipe(tap((res) => this.apiBehavior.next(res)));
}
In my component, I am subscribing to the behavior subject like this:
ngOnInit() {
this.questionsService.getQuestions()
.pipe(takeUntil(this.destroyed))
.subscribe((res) => {
this.apiResponse = res;
this.questions = res.data;
});
}
Everything is working fine up to this point. However, I have another component that sends a new value to the categoryBehaviorSubject within the service using this function:
setCategorySubject(categoryId: number | null) {
this.questionsService.setCategory(categoryId);
}
The setCategory function in my service updates the categoryBehaviorSubject with the new value and also updates the apiBehavior like this:
setCategory(categoryId: number | null) {
this.categorySubject.next(categoryId);
this.getQuestions();
}
This is the template of my component which should display questions:
<main
*ngIf="questions"
class="p-6 lg:p-20 flex max-md:flex-col gap-6 align-items-center h-full md:justify-between w-full"
>
<section class="flex flex-col gap-6 align-items-center md:w-4/5 lg:w-2/5">
<app-category-selector
class="flex justify-center align-items-center mt-6 md:hidden"
>
</app-category-selector>
<header class="font-primary text-bold text-lg text-center"><h1>{{questions.length}} Posts</h1></header>
<app-question
*ngFor="let question of questions"
[question]="question"
class="bg-secondary flex p-4 rounded h-1/4"
></app-question>
</main>
The issue here is: even though the data is successfully fetched from the API and passed to the apiBehavior Subject, the view is not updated, and new questions are never displayed when a category has been set. What could be causing this discrepancy?