Reputation: 6687
I'm trying to add this JavaScript file into my component:
https://cdn.firstpromoter.com/fprom.js
I've been provided the following function to add into my component:
$FPROM.trackSignup({
email:this.userEmail,
uid:this.userId
},
function(){
});
When adding that function, I get the console error:
ERROR in mypath/component.ts: error TS2304: Cannot find name '$FPROM'.
Seems like $FPROM
exists in that external JavaScript file, but the console isnt picking it up.
What I've done so far is created my own JavaScript file, copied the JavaScript code into it, placed that file in my component folder and then imported it at the top like so:
import './fprom.js';
and the in my component, put in the above function
I know I'm doing this incorrectly since I'm getting the console error. How can I fix this issue?
Upvotes: 0
Views: 308
Reputation: 1768
Example directive for loading Google reCaptcha which is also an external js file. You can implement a similar approach to load your js file.
Have a look at the following methods:
addScript()
-> Loads the external scriptregisterReCaptchaCallback()
-> uses the global vars once the script is loaded.export class ReCaptchaDirective implements OnInit, ControlValueAccessor {
@Input() key: string;
@Input() config: ReCaptchaConfig = {};
@Input() lang: string;
@Output() captchaResponse = new EventEmitter<string>();
@Output() captchaExpired = new EventEmitter();
private widgetId: number;
private onChange: (value: string) => void;
private onTouched: (value: string) => void;
constructor(
private element: ElementRef,
private ngZone: NgZone
) {}
ngOnInit() {
this.registerReCaptchaCallback();
this.addScript();
}
// accessing the `recaptcha` var loaded in global scope.
registerReCaptchaCallback() {
// @ts-ignore
window.reCaptchaLoad = () => {
const config = {
...this.config,
sitekey: this.key,
callback: this.onSuccess,
'expired-callback': this.onExpired
};
this.widgetId = this.render(this.element.nativeElement, config);
};
}
// method to load the external js file and add to dom
addScript() {
const script = document.createElement('script');
const lang = this.lang ? '&hl=' + this.lang : '';
script.src = `https://www.google.com/recaptcha/api.js?onload=reCaptchaLoad&render=explicit${lang}`;
script.async = true;
script.defer = true;
document.body.appendChild(script);
}
... //other captcha handler methods and code
private render(element: HTMLElement, config): number {
// @ts-ignore
return grecaptcha.render(element, config);
}
}
Note: To avoid using //@ts-ignore
in case of lint errors. You can define a simple type as well.
Upvotes: 1