11

In angular, I want to generate a MD5 hash, so I tried installing npm modules. I tried 'crypto-js', 'angular-md5', but a lot of them with no results.

Finally, I tried with 'ts-md5' and is throwing me an error, as all the others.

First npm install --save ts-md5

and then:

import {Md5} from 'ts-md5/dist/md5';
@Injectable()
export class HeroService {
    constructor(
        private MD5: Md5
    ) { }
}

But I get the error:

[Error] ERROR – Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[HeroService -> Md5]: 
  StaticInjectorError(Platform: core)[HeroService -> Md5]: 
    NullInjectorError: No provider for Md5!
get
resolveToken
tryResolveToken
[...]

Is there a better module to encrypt in md5? How can I solve this error?

3
  • 1
    Have you added Md5 to the providers array in your app.module.ts? It would seem that is all you are missing. Mar 24, 2018 at 23:27
  • MD5 is not encryption, not is a cryptographic hash function should rarely be used un new work because it is not very secure, SHS256 is a reasonable replacement for MD5.
    – zaph
    Mar 25, 2018 at 1:37
  • 3
    I know MD5 is not encryption and it's recommended to use a better system for encryption. But I need md5 to authenticate in the marvel developers api, and in this case, it must be md5 and not another one.
    – Alex
    Mar 26, 2018 at 8:34

2 Answers 2

29

Finally the best way to do it is importing it directly in the component where I have to use it and call it with new Md5().

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

const md5 = new Md5();
console.log(md5.appendStr('hello').end());

Thanks to all for the quick responses.

3
  • If you're using it like regular new Md5() constructor (and you likely should, because it cannot benefit from DI and shouldn't be a singleton), you don't need to have Md5 in the module. Mar 25, 2018 at 2:28
  • I have tried just now, and you are absolutely right. So I'm going to edit my response.
    – Alex
    Mar 26, 2018 at 16:55
  • I tried a number of Crypto / Digest libraries and this was the first that worked without any extra work. Thanks!
    – HankCa
    May 7, 2019 at 6:17
6

You cannot inject MD5 class like this, because angular dependency injection framework does not know how to provide it. You can only ask for classes that have been provided in @NgModule providers or that have been added to providers by other imported @NgModules.

You should remove private MD5: Md from the constructor and see if it works. Also check out angular cli global scripts.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.