Including a Javascript library (jsencrypt) in an Angular 2 application

I have gone through countless tutorials on this particular issue, but unfortunately, I have not yet found a solution. Let me provide some context first. I am working on an Angular 2 application and I need to incorporate this JS library for encryption: https://github.com/travist/jsencrypt

Initially, I added the jsencrypt node module using the command: npm install --save jsencrypt. The installation was successful, and I could locate the jsencrypt module in my node_modules folder.

Following some guides, I created a src/typings.d.ts file with the line: declare module 'jsencrypt'; as suggested.

Subsequently, in my components.ts file, I imported it by adding this line: import * as JSEncrypt from 'jsencrypt';

I also attempted to include < script src="/node_modules/jsencrypt/bin/jsencrypt.js">< /script>

in my .html file.

Within the initialization of my .component file, I tried to declare a basic JSEncrypt object: var decrypt = new JSEncrypt();

However, upon doing so, the console threw the following error: TypeError: Object is not a constructor (evaluating 'new WEBPACK_MODULE_4_jsencrypt()')

This led me to believe that the jsencrypt module was not being recognized correctly.

Since I am relatively new to Angular and have only been working with it for a few days, I am still learning all the terminology and fundamental concepts associated with the structural elements of an Angular application. Any guidance or assistance would be highly appreciated.

I utilized this tutorial as a starting reference point:

Answer №1

My experience with utilizing the same procedure for incorporating any JavaScript module that I have previously required has always yielded successful results.

  1. Create a new project by entering 'ng new project_name'
  2. Move into the project directory by typing 'cd project_name'
  3. Install the jsencrypt package by running 'npm install --save jsencrypt'

Following your instructions, you will now have a fully functional Angular application, with the jsencrypt package properly installed in the node_modules directory. To eliminate the TypeScript compilation messages, although not necessary for functionality:

In the src folder, establish a subfolder called @types and within it, create another directory matching the package name (e.g., jsencrypt). Inside this new folder, include an index.d.ts file like so:

  • application_root_folder/src/@types/jsencrypt/index.d.ts

The content of the index.d.ts file should solely declare the module as follows:

declare module 'jsencrypt';

To utilize the package, import it into any .ts file—such as my app.component.ts file—and begin using it:

import { Component } from '@angular/core';
import * as JsEncryptModule from 'jsencrypt';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'app';

    constructor() {
        var encrypt = new JsEncryptModule.JSEncrypt();
        console.log(encrypt);
    }
}

You can verify in your browser's console that the object contains all properties and methods provided by the module/package:

https://i.sstatic.net/IZeb6.png

I won't delve extensively into the specifics of the package's usage itself, as I'm unfamiliar with it and believe it isn't the focal point of the inquiry. I trust this information proves to be helpful!

Answer №3

Include encryption functionality

import EncryptionModule from 'encryption-module/encrypt';

Initialize encryption module

private encryptor: EncryptionModule;

Configure public key

  private setupEncryption(): void {
    this.publicKey = this.storage.getItem('publicKey');

    if (this.publicKey) {
      this.encryptor = new EncryptionModule();
      this.encryptor.setPublicKey(this.publicKey);
    }
  }

Answer №4

const { JSEncrypt } = require('jsencrypt');

Give this a shot. It specifically imports the JSEncrypt class.

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

The presence of double quotes in stringified JSON is undesired

I am currently working on a weather forecasting website where the API returns pure JSON data. However, when I convert this data to a string and add it to an element in order to display it on the webpage, I encounter a problem with double quotes appearing. ...

Passing back function results in an IONIC application

Currently, I am studying IONIC 5 and working with the native geolocation feature to fetch latitude and longitude coordinates. My goal is to retrieve these coordinates and then send them to a server via a form. geolocate() { this.geolocation.ge ...

Typescript is missing Zod and tRPC types throughout all projects in the monorepo, leading to the use of 'any'

Recently, I've found myself stuck in a puzzling predicament. For the last couple of weeks, I've been trying to troubleshoot why the types are getting lost within my projects housed in a monorepo. Even though my backend exposes the necessary types ...

Updating directives is required when there is a modification in the input

I created a custom directive that controls the opacity of an element based on an input value: import { Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core'; import { Observable, Subscription } from 'rxjs/Rx'; @Dir ...

Is it possible for two Bootstrap icon class names to be used sequentially with one taking precedence over the other?

I am having an issue with toggling a class name in my code. I have a class named (bi bi-clipboard) and I want to change it to (bi-clipboard-check) when it is clicked. However, the problem is that the new class name gets added next to the existing one like ...

Take action once the Promise outside of the then block has been successfully completed

Presented below is the code snippet: function getPromise():Promise<any> { let p = new Promise<any>((resolve, reject) => { //some logical resolve(data); }); p.finally(()=>{ //I want do something when ou ...

I am interested in extracting information from a public Facebook post

Is it possible to scrape or utilize the FB API to retrieve data from a public profile's wall post? By inspecting the element on the URL, you can see most of the data as well as the ajax calls for infinite scrolling on the wall. How could one go about ...

Having trouble with your custom AngularJS directive not functioning correctly?

I am facing an issue with my custom directive implementation. I have a custom directive that contains a table which references a controller. The ProjectController part works fine when it is not included in the code, but as soon as I put everything into the ...

I'm surprised by the fact that array.findIndex is not functioning properly. According to Mozilla, it should be working fine

It was necessary to change state.findIndex to state.ids.findIndex in order to resolve the issue I was facing. However, an unexpected behavior occurs when calling the function onClick, as it automatically updates ALL of the active values to true, instead o ...

What could be causing the issue with setting a value for a JSON array in the following method?

Consider this piece of code that I'm currently working with: compareList[productName] = productID + ',' + productHref; console.log(productName + ' ' + productID + ' ' + productHref + ' ' + compareList.length); ...

SwitchMap in Typescript allows you to switch to a

In my TypeScript code, I have implemented multiple interfaces, components, and a key/interface map. interface FooProps { 'keyInFoo': string } const Foo = (props: FooProps) => {} interface BarProps { 'keyInBar': string } cons ...

Utilizing various Material UI Sliders on a single page with shared color properties

After creating a component called "SliderBox", I noticed that it returns a div containing a Material UI Slider with createMuiTheme and an input component. The "SliderBox" component utilizes an onHover method on the parent div to change the component' ...

Optimizing Angular: Configuring baseHref for assets during development with SSR

During production, we set the base href using the following command: ng build --base-href /app/ This configuration works smoothly as our assets are also accessible at /app/assets/, just as expected. However, I have been facing difficulties achieving the ...

Identify the externally-sourced element of interest

I'm attempting to apply a ScrollReveal effect to an element loaded from a separate html file called "header.html". Unfortunately, the ScrollReveal animation is not working on this particular element, while other elements within my index.html are funct ...

What are the best ways to make this date more visually appealing and easy to understand?

Hey there! So I have a date that looks like this: 2022-06-28T17:09:00.922108+01:00 I'm trying to make it more readable, but unfortunately, when I attempted using moment-js in my javascript/react project, it threw an error stating "invalid format". ...

What is the alternative parameter to use instead of onChange in React Router v4?

Having an issue with the onChange Prop in TypeScript and React JS: I am encountering an error message saying "No overload matched this call." <HashRouter> <Switch> <Route path="/" ...

The Angular 2.0 HTTP post request encountered an error when trying to respond with a status of 200 Ok for a null

I'm currently attempting to post data using http in Angular 2. I have added an http call with the corresponding API, and when I click the button, it should send data to my database. However, an error is showing up in the console. XMLHttpRequest canno ...

Upcoming JWT authentication module

I've been working on a simple application using next.js and integrating JWT for user authentication. My goal is to have a single navbar and layout that can dynamically adjust based on the authentication status. Below is my code: import React from "r ...

Establishing the request body for RESTful web services utilizing the POST technique

Hey there, I'm currently working on creating a REST response using the POST method. I want to pass variables dynamically instead of hardcoding them. However, I am encountering an issue when trying to send an array as a parameter to the REST web servic ...

What is the best way to send a JSON response from a Symfony2 controller?

I am utilizing jQuery to modify my form, which is created using Symfony. The form is displayed within a jQuery dialog and then submitted. Data is successfully stored in the database. However, I am unsure if I need to send some JSON back to jQuery. I am ...