Use jQuery in Angular/Typescript without a type definition

Comments

Gravatar Image
Jacek Mówiński 1/1/2019 9:33:14 PM
Sorry but this is wrong. The injection token method is used to get rid of dependency on global variables. So in this example to get rid of this: declare let jQuery: Object; What You're doing here is referencing the global variable in Your module and then registering that with di, which completely misses the point. What You want to do here is: 1. Remove "declare let jQuery: Object;" 2. In App.Module.ts remove: "{ provide: JQ_TOKEN, useValue: jQuery }" and replace it with either of these: { provide: JQ_TOKEN, useFactory: jQueryFactory } or JQUERY_PROVIDER This will yield the result You wanted to achieve.
Gravatar Image
Jeffrey Rosselle 1/2/2019 3:58:54 PM
Hi Jacek, thanks for your feedback! If used this piece of code in the verry beginning of Angular. It was used start my Bootstrap carrousel. It did work though. Angular probably changed some internals which maken it unusable now. I’ll check it out and change this post if needed.
Gravatar Image
Jacek Mówiński 1/2/2019 5:08:25 PM
It should technically be functional. It's conceptually flawed due to reasons described above. In brief You created a service with a factory, but instead of using it, You're using a global reference.
Gravatar Image
Jeffrey Rosselle 1/6/2019 3:40:33 PM
Hi Jacek, I adjusted the code after your feedback. I should have tried to understand the code a bit more, before posting it, instead of just being happy with 'it works'. Thanks again!
Gravatar Image
Ehouarn Perret 7/21/2018 7:42:00 PM
Why favor injection token strategy over the type definitions one?
Gravatar Image
Jeffrey Rosselle 9/24/2018 2:16:00 PM
Apologies for the late reply. I don’t really favor one above the other. It’s just a quick way without using any other extra packages
Gravatar Image
mtringel 1/29/2018 11:55:00 AM
I got “NodeInvocationException: No provider for InjectionToken jQuery!” unfortunatelly
Gravatar Image
Jeffrey Rosselle 1/6/2019 10:24:05 PM
Have you added the Jquery_provider to your app.module.ts?
Gravatar Image
David 9/12/2017 8:12:00 PM
Your solution leads to : TS7017: Element implicitly has an ‘any’ type because type ‘Window’ has no index signature.
Gravatar Image
Jeffrey Rosselle 10/16/2017 8:59:00 AM
I can’t seem to reproduce this. Are you maybe using lib.d.ts? As stated here https://stackoverflow.com/questions/42193262/element-implicitly-has-an-any-type-because-type-window-has-no-index-signatur it does not have index in it’s signature so it cannot find the window.