Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 convert string to md5 hash

I found the ts-md5 package but in the example it has a hashStr method but now it doesn't.

Property 'hashStr' does not exist on type Md5.

That error is logged in my console after using that. How can I do that?

I tried inject it in constructor

constructor(private _md5: Md5) {}

and then

let a: any = this._md5.hashStr("password");
like image 619
gsiradze Avatar asked Feb 11 '17 18:02

gsiradze


1 Answers

I just checked out the documentation and source code, and the hashStr method doesn't exist on instances of the Md5 class.

This means that if you only need to use the hashStr method, you don't need to initialize the class in your constructor since you can just call the method directly on the Md5 class:

let hash = Md5.hashStr("password");

If you want to generate the hash from an instance (rather than the class), then you would use the appendStr method and then chain the end() method:

let hash = _md5.appendStr('password').end();

Also, since you're using Angular 2, remember to add the Md5 class in your component's providers array if you are initializing it in your constructor:

import { Md5 } from 'ts-md5/dist/md5';

@Component({
  // ...
  providers: [Md5]
})
export class ExampleComponent {
  constructor(
    private _md5: Md5
  ) {
    let hash = Md5.hashStr("password");

    // or ...

    let hash2 = _md5.appendStr('password').end();
  }
}
like image 125
Josh Crozier Avatar answered Oct 30 '22 00:10

Josh Crozier