Implementing atob in Angular's interface

Looking for a solution to a token storage issue, my initial thought is that interfaces might be the way to go. Presently, my login code looks like this:

import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

interface User {
  success: {
    id: number;
    role: string;
    accessToken: string;
    refreshToken: string;
    lifetime: {
      epoch: number;
      timeZone: number;
    }
  }
}

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
})

export class LoginComponent {
  constructor( private fb: FormBuilder, private http: HttpClient ) { }

  loginInfo = this.fb.group({
    email: [''],
    password: ['']
  })

  onSubmit() {
    this.http.post<User>('', this.loginInfo.value)
      .subscribe(x => localStorage.setItem("currentUser",JSON.stringify(x)))
  };
}

The challenge lies in dealing with refreshToken and accessToken coming in as Base64 encoded strings, which I believe can only be resolved using the atob() function. Is there a way to address this within the interface?

I'm aware the code snippet below doesn't function, but it aims to clarify the goal:

interface User {
  success: {
    id: number;
    role: string;
    accessToken: atob(string);
    refreshToken: atob(string);
    lifetime: {
      epoch: number;
      timeZone: number;
    }
  }
}

Answer №1

If you're looking to convert the base64 token using a getter in a class interface, here's an example of how you can achieve it:

class SuccessfulUser {
  id: number;
  role: string;

  get accessToken(): string {
    return atob(this._accessToken);
  }
  set accessToken(value: string) {
    this._accessToken = value;
  }
  private _accessToken?: string;

  get refreshToken(): string {
    return atob(this._refreshToken);
  }
  set refreshToken(value: string) {
    this._refreshToken = value;
  }
  private _refreshToken?: string;

  lifetime: {
    epoch: number;
    timeZone: number;
  }
}

class UserInterface {
  success: SuccessfulUser;
}

Implementing directly on the interface is not feasible. Hopefully, this solution helps.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to execute an Nx executor function using Node.js?

Can a customized Nx executor function be executed after the app image is built? This is the approach I am taking: "migrate-up": { "executor": "@nx-mongo-migrate/mongo-migrate:up", "options": { &q ...

What are the best practices for securely storing SSL certificates and public/private keys?

I possess keys that appear like this. MIID0DCCArigAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJGUjET MBEGA1UECAwKU29tZS1TdGF0ZTEOMAwGA1UEBwwFUGFyaXMxDTALBgNVBAoMBERp bWkxDTALBgNVBAsMBE5TQlUxEDAOBgNVBAMMB0RpbWkgQ0ExGzAZBgkqhkiG9w0B CQEWDGRpbWlAZGltaS5mcjA ...

What steps should I take to resolve this unexpected issue with svelte?

Whenever I attempt to execute the application, an error is consistently displayed to me. Here is a screenshot of the error: https://i.sstatic.net/jfo3X.png This issue always arises on the initial import type line, regardless of the content or arrangement ...

What is the best way to find a partial string match within an array of objects when using Jest?

I am currently utilizing the following versions: Node.js: 9.8.0 Jest: 22.4.2 A function called myFunction is returning an array structured like this: [ ... { id: 00000000, path: "www.someUrl.com/some/path/to" } ... ] I ...

A guide to resolving the Angular 11 error of exceeding the maximum call stack size

I am currently working with 2 modules in Angular 11 CustomerModule AccountingModule I have declared certain components as widget components in these modules that are used interchangeably: CustomerModule -> CustomerBlockInfoWidget AccountingModule -&g ...

When the first element of an array is undefined, Angular's ngFor will not render anything

We have an array called stringArray: var stringArray = new Array(); stringArray[1] = 'one'; In Angular, the ngFor directive displays nothing when stringArray[0] is undefined. How can this issue be resolved? ...

Exploring the Concept of Typescript Generics with Arrays and Adding Items

Currently, I am exploring the concept of creating a versatile function that can handle arrays of various types with only a few common properties. The goal is to enable simple operations like adding or removing elements from these arrays. What would be the ...

Is it possible to meet the requirements of a specific interface using an enum field as the criteria?

I've been struggling to create a versatile function that can return a specific interface based on an enum argument, but all my attempts have failed. Could it be possible that I missed something or am simply approaching it the wrong way? If I try to ...

Error in Nestjs Swagger: UnhandledPromiseRejectionWarning - The property `prototype` cannot be destructed from an 'undefined' or 'null' object

Currently, I am in the process of developing a Nestjs REST API project and need to integrate swagger. For reference, I followed this repository: https://github.com/nestjs/nest/tree/master/sample/11-swagger However, during the setup, I encountered the foll ...

Why does `window.location.reload()` only refresh the home page and not the other pages when using Angular?

After transitioning from the home page to the menu page, I expect the menu page to refresh automatically once. However, when implementing the code below, the home page is refreshed first before navigating to the menu page without an auto-refresh. 1)Initia ...

What is the meaning of a "hook" in the world of HTML?

During a recent interview, a developer asked me about the "hooks" Angular uses with HTML. I admitted that I was not familiar with the term "hook," despite my extensive experience in web development over the past two decades. While I have some ideas of what ...

Getting Typescript Compiler to Recognize Global Types: Tips and Strategies

In the top level of my project, I have defined some global interfaces as shown below: globaltypes.ts declare global { my_interface { name:string } } However, when attempting to compile with ts-node, the compiler fails and displays the er ...

What causes the placeholder to be invisible in a select/option when ngModel is used?

While using a select with ngModel to capture the value of the options, I noticed that when I render it, there is no placeholder displayed as shown in the image below: This is the code snippet: <select [value]="selected_tipo" [(ngModel)]=&q ...

Firebase Cloud Function Local Emulator Fails to Retrieve Data with Error 404

My goal is to locally trigger a Firebase Cloud Function using the emulator. However, every time I try, the function returns a 404 Not Found status code and a response body of Cannot Get. The function is deployed locally and visible on the UI, but it fails ...

The TypeScript Promise error codes TS2304 and TS2529 are causing confusion among

I came across the code below: function asyncTask(): Promise<string> { return new Promise<string>(resolve => resolve); } This code resulted in the following error: TS2304: cannot find name 'Promise' To address this issue, ...

Oops! An issue occurred: [RunScriptError]: Running "C:Windowssystem32cmd.exe /d /s /c electron-builder install-app-deps" resulted in an error with exit code 1

query: https://github.com/electron/electron/issues/29273 I am having trouble with the installation package as it keeps failing and showing errors. Any tips or suggestions would be highly appreciated. Thank you! ...

Parsing values from deeply nested objects and arrays

I've come across this issue before, but I'm having difficulty navigating through a nested structure. I can't seem to find any guidance in the right direction. Here is the object I'm attempting to parse: const nestedArray = { id ...

Circular dependency situation encountered in Angular 2 shared module

I'm currently working on a share module setup that is structured as follows: @NgModule({ exports: [ CommonModule, HttpModule, OneModule, TwoModule ] }) export class SharedModule { } The OneModule imports the SharedModule in order ...

Tips on utilizing the i18n t function within a TypeScript-powered Vue3 component

I am working on creating a control that can automatically manage interpolation for internationalization (i18n) strings: <script lang="ts"> import { ref, defineComponent, inject } from "vue"; import type { InterpolationItem, Inter ...

Users are reporting a problem with the PrimeNG confirmation dialog where it becomes unresponsive and locks up the screen

Previously functioning code seems to have been affected by an update to PrimeNG. The confirmation dialog that was once usable is now hidden behind a gray click-mask, rendering everything on the screen unclickable: https://i.sstatic.net/YN7Iu.png The HTML ...