简体   繁体   中英

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");

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();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM