typescript 如何在 Angular 4 cookie 中设置,键入数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43920147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:32:31  来源:igfitidea点击:

How to set in Angular 4 cookies, type number values

angulartypescriptcookiessession-cookies

提问by Diego

I'm beginning to develop in angular 4 with typescript. I want to save info in cookies. I'm using "ngx-cookie". Put method, just accept for the value as type string and I want to save a number type var. What the best approach for that?

我开始使用打字稿在 angular 4 中进行开发。我想在 cookie 中保存信息。我正在使用“ ngx-cookie”。Put 方法,只接受作为字符串类型的值,我想保存一个数字类型 var。最好的方法是什么?

Explanation foundJavascript - Using cookies to store an integer

解释发现Javascript - 使用 cookie 来存储一个整数

Cookies in browsers are strings, that seems the reason

浏览器中的 Cookie 是字符串,这似乎是原因

回答by astro8891

In typescript you can use the 'any' type to store values to get around being specific with strong types.

在打字稿中,您可以使用 'any' 类型来存储值以避开特定于强类型的问题。

var myInteger: any;
var myString: any;

myInteger = 1 //valid
myString = "helloWorld" //valid

As ngx-cookie put method takes a string you would need to pass a string. I would call JSON.stringify on your object and pass that to the put request.

由于 ngx-cookie put 方法需要一个字符串,因此您需要传递一个字符串。我会在您的对象上调用 JSON.stringify 并将其传递给放置请求。

saveSearchCritereaCookie = new myCookieObject();
var searchCookie: String = JSON.stringify(saveSearchCritereaCookie);

* @param {string} key Id for the `value`.
 * @param {string} value Raw value to be stored.
 * @param {CookieOptions} options (Optional) Options object.
 */

put(key, searchCookie, options?): void;

Please see the ngx-cookie documentation page for more examples: NGX-Cookie

有关更多示例,请参阅 ngx-cookie 文档页面:NGX-Cookie