简体   繁体   English

以角度在会话存储中设置多个值

[英]Setting multiple values in session storage in angular

I am trying to send a object and an int to the storage on a click event.我正在尝试在单击事件时将一个对象和一个 int 发送到存储。 They need to be mapped together.它们需要映射到一起。 I don't know the syntax for this.我不知道这个的语法。

HTML with onClick changes-带有 onClick 更改的 HTML -

 <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- Service.ts 文件-

 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 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.但是,通过这种方式您无法轻松存储多部电影或通过 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:通过这种方式,您可以通过 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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM