如何在Angular 2中使用base64对字符串进行编码或解码?
我的前端工具是Angular 2。我有一个密码字符串,在传递给API之前需要进行base64编码。由于在服务中,base64编码的字符串将被解码。
因此,我正在寻找一些用于Angular2/Typescript的base64编码/解码库以及一些选项。
谢谢!!!
如何在Angular 2中使用base64对字符串进行编码或解码?
我的前端工具是Angular 2。我有一个密码字符串,在传递给API之前需要进行base64编码。由于在服务中,base64编码的字符串将被解码。
因此,我正在寻找一些用于Angular2/Typescript的base64编码/解码库以及一些选项。
谢谢!!!
自Angular 12起,btoa()
和atob()
函数已被弃用。请改用以下函数:
TextEncoder.encode()
和 TextDecoder.decode()
console.log(Buffer.from("Hello World").toString('base64'));
// SGVsbG8gV29ybGQ=
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('binary'))
// Hello World
注意:您必须显式编码!在 Angular2 中进行 base64 编码,您可以使用 btoa() 函数。
示例:
console.log(btoa("stringAngular2"));
// Output:- c3RyaW5nQW5ndWxhcjI=
在Angular2中,如果需要将base64解码,可以使用atob()函数。
例如:
console.log(atob("c3RyaW5nQW5ndWxhcjI="));
// Output:- stringAngular2
使用btoa("你的字符串")
更多信息:https://developer.mozilla.org/zh-CN/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
TypeScript是Javascript的超集,它可以使用现有的Javascript库和Web API。
btoa()
进行编码,使用atob()
进行解码。text_val:any="your encoding text";
编码文本:console.log(btoa(this.text_val)); //eW91ciBlbmNvZGluZyB0ZXh0
解码文本:console.log(atob("eW91ciBlbmNvZGluZyB0ZXh0")); //你的编码文本
npm install turbocommons-ts
然后调用你需要的方法:
import { ConversionUtils } from 'turbocommons-ts';
console.log(ConversionUtils.stringToBase64('hello'));
console.log(ConversionUtils.base64ToString('aGVsbG8='));
这个库是开源的,并经过了广泛的测试。更多信息请参见此处:
https://turboframework.org/en/blog/2022-10-26/encode-decode-base64-strings-javascript-typescript-php