如何将CryptoJS与Angular 4一起使用

如何将CryptoJS与Angular 4一起使用,angular,cryptojs,Angular,Cryptojs,当我不使用Angular 4时,我只会为库添加脚本标记。即使我将脚本标记放在index.html文件中,它也无法识别CryptoJS。有没有一种方法可以使用库或角度等效物 使用NPM安装,并在组件文件中导入下面的语句 npm install crypto-js import * as crypto from 'crypto-js'; 现在,您可以在组件文件中使用crypto。使用以下命令安装cryptoJS npm install crypto-js --save 然后,您可以构建一个服务

当我不使用Angular 4时,我只会为库添加
脚本
标记。即使我将
脚本
标记放在
index.html
文件中,它也无法识别
CryptoJS
。有没有一种方法可以使用库或角度等效物

使用NPM安装,并在组件文件中导入下面的语句

npm install crypto-js

import * as crypto from 'crypto-js';

现在,您可以在组件文件中使用crypto。

使用以下命令安装cryptoJS

npm install crypto-js --save
然后,您可以构建一个服务服务

import { Injectable } from '@angular/core';
import * as CryptoJS from 'crypto-js';

@Injectable({
  providedIn: 'root'
})
export class AESEncryptDecryptService {

  secretKey = "YourSecretKeyForEncryption&Descryption";
  constructor() { }

  encrypt(value : string) : string{
    return CryptoJS.AES.encrypt(value, this.secretKey.trim()).toString();
  }

  decrypt(textToDecrypt : string){
    return CryptoJS.AES.decrypt(textToDecrypt, this.secretKey.trim()).toString(CryptoJS.enc.Utf8);
  }
}
在组件中,导入并注入此服务

import { AESEncryptDecryptService } from '../services/aesencrypt-decrypt.service'; 


constructor(private _AESEncryptDecryptService: AESEncryptDecryptService) { }
使用加密/解密函数

let encryptedText = _self._AESEncryptDecryptService.encrypt("Hello World");
let decryptedText = _self._AESEncryptDecryptService.decrypt(encryptedText);
导入文件时,Angular 6应包括以下内容:

import * as cryptoJS from 'crypto-js';

我还将添加
npm install@types/crypto js
以获得类型