angelo
angelo

Reputation: 11

Json stringify a map contains map and objects Angular

sorry for my english :)

i have a service , i need to stock it in storage , i make a mutliple caddies.But i have a probleme to use stringify for put mycaddies in string .. :

export class CaddyService {

   currentCaddyName:string="Caddy1";
  public caddies:Map<string,Caddy> = new Map();

}

i need to stock it in storage , i make a mutliple caddies:

localStorage.setItem('myCaddies',JSON.stringify(this.caddies));

and parse after in my constructor:

let caddies= localStorage.getItem('myCaddies');

but it doesn't work , the probleme that this caddies contains another map and object:

export class **Caddy**{

    constructor (public name:string){

    }


    public items:Map<number,ProductItem> = new Map();
    public client:Client;
}

export class **ProductItem** {



    public product:Product;
    price:number;
    quantity:number;
}


export interface Product{
    id:number;
    name:string;
    description:string;
    currentPrice:number;
    promotion:boolean;
    selected:boolean;
    available:boolean;
    photoName:string;
    quantity:number;
    _links:{
      self:{
        href:string;
      },
      product:{
        href:string;
      },
      category:{
        href:string
      }
    }

  }


export class Client {
    name:string;
    emai:string;
    phoneNumber:string;
    address:string;
    username:string;
}

thanks

Upvotes: 1

Views: 185

Answers (1)

Wandrille
Wandrille

Reputation: 6811

If you want a simple solution:

  • use an object instead of new Map() because it can use stringify
caddies:{[key:string]:Caddy}

All the method inside Map can be gotten with: Object.keys(), Object.values() ...

Edit: I haven't seen that Caddy was also an object. In this case, it won't work. So two others solutions:

  • Use an interface instead of a class and use a service for the methods which were inside the class.
  • or create a method inside the class Caddy to map to an object. And also, a constructor to map object to the class.

Upvotes: 1

Related Questions