Angular 2 convert string to md5 hash

怎甘沉沦 提交于 2019-12-12 11:33:10

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/42179618/angular-2-convert-string-to-md5-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!