I am trying to send a object and an int to the storage on a click event. They need to be mapped together. I don't know the syntax for this.
HTML with onClick changes-
<button class="btn btn-outline-danger w-100 my-2 my-sm-0" (click)="onAddCart(movie, movie.aPrice)">Rent</button> <button class="btn btn-outline-danger w-100 my-2 my-sm-0" (click)="onAddCart(movie, movie.aPurchasePrice)">Purchase</button>
In the service, I want to map that price to the object I am sending. How do i update the functions according to this.
Service.ts file-
addMovieToCart(movies: any,price : number) { sessionStorage.setItem('movie', JSON.stringify(movies)); } getMovieFromCart() { return JSON.parse(sessionStorage.getItem('movie')); } removeAllMovieFromCart() { return sessionStorage.removeItem('movie'); }
You can use spread operator.
export class AppComponent {
public obj: {} = {"name": "peter"};
constructor() {
console.log (this.obj);
console.log ({...this.obj, "age": 22});
}
}
https://stackblitz.com/edit/simple-spread-operator?file=src/app/app.component.ts
The first step would be to store both the movie and its price in the same object:
const record = { movie, price };
sessionStorage.setItem('movie', record);
However this way you can't easily store multiple movies or retrieve them by id.
A better approach would be to store all movies in a shared object.
const record = { movie, price };
// Default to empty dictionary if there is no movies record yet.
const existingMoviesJSON = sessionStorage.getItem('movies') || '{}';
const movies = JSON.parse(existingMoviesJSON);
// Assuming your movie has an id, but you could also use a unique name.
movies[movie.id] = record;
sessionStorage.setItem('movies', JSON.stringify(movies));
This way you can then retrieve movies with their price by id:
getMovieFromCart(movieId) {
const movies = JSON.parse(sessionStorage.getItem('movies') || '{}');
// Will return undefined if the movieId can't be found in the dictionary so be sure to handle this error.
return movies[movieId];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.