encrypt the text using cryptojs library in angular

2020-07-18 08:41发布

问题:

I am using cryptojs library for encrypting password text and sending the data to server. But i am getting the following error saying,

Error TS2304: Cannot find name 'CryptoJS'. 

I installed the library in the following way: sudo npm install crypto-js

import 'crypto-js/crypto-js';
@Page({
  templateUrl: 'build/pages/login/login.html'
})
export class LoginPage {
  constructor(private nav: NavController, public http: Http) {

  }    

  validateUser(fieldval, data){
    let params = "{'ignoreAuthModule': 'ignoreAuthModule'}";
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append('Parameter',  params);
    let url = 'app/authentication';
    let encrypted_password = Cryptojs.AES.encrypt(fieldval.password, CryptoJS.enc.Base64.parse(data.seed),{mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }).toString().replace(/\+/g, "-").replace(/\//g, '_');

    let requestoptions = new RequestOptions({
      method: RequestMethod.Post,
      url: url,
      headers: this.headers,
      body: JSON.stringify(data)
    })  

    let body = JSON.stringify(params); 

    this.http.post(url, body, headers)
      .subscribe(
        response => {          
        },
        error => {
          console.log(error.text());
        }
      );        
  }            
  logError(err) {
    console.error('There was an error: ' + err);
  }
}

回答1:

I don't know where this compilation error occurs but you should install the typings for the crypto-js library:

typings install --ambient crypto-js

See this question for more details:

  • How to import non-core npm modules in Angular 2 e.g. (to use an encryption library)?