1

i'm trying to view inside page.html file some data comes from API and this data is only long text encode via base64 , well the problem is i want to decode the text inside html file not at page.ts file so i tried many logic for that but nothing works with me . example inside HTML file:

  • {{item.text|| base64}}
  • {{item.text|| decodeURIComponent}}
  • {{item.text|| atob}}
  • atob({{item.text}})

but nothing works . inside TS page i tried to use decodeURIComponent(escape(window.atob(ielement.text))) and it's working but i want from html page

this is the text comes from API : aGVsbG8gd29ybGQh

thanks in advance ..

1 Answers1

0

You can create an Angular Pipe for decode base64 string like below:

import { Pipe, PipeTransform } from '@angular/core';
/*
 * Usage:
 *   value | decodeBase64
 * Example:
 *   {{ 'aGFyZXNo' | decodeBase64 }}
 *
*/
@Pipe({name: 'decodeBase64'})
export class DecodeBase64Pipe implements PipeTransform {
  transform(value: string): string {

    return decodeURIComponent(escape(window.atob(value)));
  }
}

and use this pipe as below in your HTML:

<p>Decoded text: {{'aGFyZXNo' | decodeBase64}}</p>

You need to add Pipe in you app.module file to register.

H_H
  • 1,460
  • 2
  • 15
  • 30
  • thank you so much , this is good way to do the correct logic but i get one error message, https://i.imgur.com/fRgH6gN.png https://i.imgur.com/4PtL4Xx.png and this mean i have to declare escape and i do like that : #declare function escape(s: string): string; and after that i get one more message https://i.imgur.com/AZQvXxo.png thanks in advance – Hecham Al Sayed Ahmad Jan 20 '19 at 19:35
  • the issue is fixed by edit "return" of class DecodeBase64Pipe old code : return decodeURIComponent(escape(window.atob(value))); new one : return decodeURIComponent(atob(value).split('').map(function (c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); – Hecham Al Sayed Ahmad Jan 21 '19 at 05:09