Currently, I am in the process of developing a build-a-burger website using Angular. The ingredients and inventory need to be updated dynamically based on the selected location. Users can choose the location from a dropdown menu in the navigation bar.
The issue I'm facing is that every time I update the location in session storage, I have to manually refresh the page for the new inventory to load. Is there a way to make it automatically render the updated inventory when the location changes in session storage?
Here is my app.component.html:
<select id="locations" appAuthOnly [isVerified]="isVerified" [(ngModel)]="selectedLocation" (change)="onLocationChange()">
<option value="Mystic Falls">Mystic Falls</option>
<option value="Riverdale">Riverdale</option>
<option value="Sunnydale">Sunnydale</option>
This is the app.component.ts:
ngOnInit() {
this.isVerified = localStorage.getItem('token') ? true : false;
console.log(this.selectedLocation);
this.selectedLocation = sessionStorage.getItem('selectedLocation') || 'Mystic Falls';
}
onLocationChange() {
sessionStorage.setItem('selectedLocation', this.selectedLocation);
}
UPDATED:
onLocationChange() {
sessionStorage.setItem('selectedLocation', this.selectedLocation);
this.ingrediantService.getAllItems();
}
}
My ingrediants.service.ts:
selectedLocation: string = sessionStorage.getItem('selectedLocation') ?? '';
getAllItems(): Observable<Ingrediant[]> {
const selectedLocation = sessionStorage.getItem('selectedLocation') ?? '';
return this.http.get<Ingrediant[]>(this.url).pipe(
map(ingredients => ingredients.filter(ingredient => ingredient.location === selectedLocation))
);
}
And lastly - inventory-ingrediants.component.ts:
ngOnInit() {
// Retrieve the ingredients
this.ingrediantService.getAllItems().subscribe((data) => {
console.log(data);
this.breadIngrediants = data.filter(ingredient => ingredient.category === 'Bread');
this.pattyIngrediants = data.filter(ingredient => ingredient.category === 'Patty');
this.cheeseIngrediants = data.filter(ingredient => ingredient.category === 'Cheese');
this.garnishIngrediants = data.filter(ingredient => ingredient.category === 'Garnish');
this.sauceIngrediants = data.filter(ingredient => ingredient.category === 'Sauce');
});
this.carousel = this.elementRef.nativeElement.querySelector('.carousel-container');
this.arrowLeft = this.elementRef.nativeElement.querySelector('.arrow-left');
this.arrowRight = this.elementRef.nativeElement.querySelector('.arrow-right');
// Subscribe to the watchSessionStorage method to listen for changes to the session storage
};