字符串以角度(2 +)编码和解码

如何编码或解码一个字符串在角度2与基64? ? ? 我的前端工具是角度2。我有一个密码字符串,在传递给 API 之前,我需要 base64编码。因为在服务基64编码字符串将被解码。

因此,我正在寻找一些基于64编码/解码库 Angular2/类型和一些选项。

谢谢! ! !

249743 次浏览

Use the btoa() function to encode:

console.log(btoa("password")); // cGFzc3dvcmQ=

To decode, you can use the atob() function:

console.log(atob("cGFzc3dvcmQ=")); // password

Use btoa("yourstring")

more info: https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

TypeScript is a superset of Javascript, it can use existing Javascript libraries and web APIs

For encoding to base64 in Angular2, you can use btoa() function.

Example:-

console.log(btoa("stringAngular2"));
// Output:- c3RyaW5nQW5ndWxhcjI=

For decoding from base64 in Angular2, you can use atob() function.

Example:-

console.log(atob("c3RyaW5nQW5ndWxhcjI="));
// Output:- stringAngular2

Use btoa() for encode and atob() for decode

text_val:any="your encoding text";

Encoded Text: console.log(btoa(this.text_val)); //eW91ciBlbmNvZGluZyB0ZXh0

Decoded Text: console.log(atob("eW91ciBlbmNvZGluZyB0ZXh0")); //your encoding text

From Angular 12 btoa() and atob() functions are deprecated. Use these instead:

console.log(Buffer.from("Hello World").toString('base64'));
// SGVsbG8gV29ybGQ=
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('binary'))
// Hello World

Note: you must explicit encoding!

If you want a more complete solution, you can use the turbocommons library. Just install it:

npm install turbocommons-ts

And then call the method you need:

import { ConversionUtils } from 'turbocommons-ts';


console.log(ConversionUtils.stringToBase64('hello'));
console.log(ConversionUtils.base64ToString('aGVsbG8='));

This library is open source and extensively tested. More info here:

https://turboframework.org/en/blog/2022-10-26/encode-decode-base64-strings-javascript-typescript-php