Search code examples
javascriptangularcookiesangular6ngx-cookie-service

Angular 8 save array in cookie


I am using ngx-cookie-service package

{
    "user": [
        {
            "id": 109,
            "name": "name1",
            "job" : "job name"

        }
    ],
    "token":"xxxx"
}

    this.cookieService.set( 'user_id', result.user.id );
    this.cookieService.set( 'user_name', result.user.name );
    this.cookieService.set( 'user_job', result.user.job );

How can I save this as a JSON array instead of saving individual?

like this.cookieService.set( 'user', result.user );


Solution

  • You can use stringify() and save it and then parse() to get the value back

    To set the value:

    this.cookieService.set('user', JSON.stringify(result));
    

    To retrieve the value:

    JSON.parse(this.cookieService.get('user'));