How to use methods from external js in Angular - javascript

I need to call a function from external js file into my Angular component
I already go through the related question
How can i import external js file in Angular 5?
How to include external js file in Angular 4 and call function from angular to js
My External JS (external.js)
var radius = 25;
function calculateRadius(pi) {
let piValue = 3.14159;
if(pi) {
piValue = pi;
}
var result = piValue * radius * radius;
console.log('Result: ', result);
}
function wrapperMethod(pi) {
console.log('Hi, this is from wrapper method');
calculateRadius(pi)
}
I added the said JS file in the angular.json under scripts block
"scripts": [
"src/assets/external.js",
]
In the CircleComponent, I would like to call the method
import wrapperMethod from '../../src/assets/external.js';
#Component({
selector: 'app-circle',
templateUrl: './circle.component.html',
styleUrls: ['./circle.component.css']
})
export class CircleComponent implements OnInit {
constructor() { }
ngOnInit() {
wrapperMethod(3.14159);
}
}
But its failing to call the method. Kindly assist me how to achieve this.
Note: The said methods as just an example methods, I want to implement this logic with the complex code file. The said question tells about typings.d.ts, but I don't know where is typings.d.ts in my Angular project. Kindly brief me regarding this. If the said question gives good solution means, why should I post this question.
Angular Structure (Created using Angular CLI)
I don't know where is typings.d.ts, could anyone please tell me where is typings.d.ts - which is mentioned in the said questions How to include external js file in Angular 4 and call function from angular to js

You can follow this below steps
1) First add a reference of your external JS file for importing it to the component.
import * as wrapperMethods from '../../src/assets/external.js';
2) Now declare a "var" of the same name that your function has inside external JS.
declare var wrapperMethods: any;
3) ngOninit(){
wrapperMethods();
}

put your external .js file under scripts in build
if still can not see methods inside it put in in index.html
<script src="assets/PATH_TO_YOUR_JS_FILE"></script>
in your component after import section
declare var FUNCTION_NAME: any;
ANY_FUNCTION() {
FUNCTION_NAME(params);
}

Don't get confused with typings.d.ts. Follow below steps.
1.Add your external file inside assets folder. The content of this file will be by default included as per your angular-cli.json.
2.The function of your js which you're going to use must be exported. i.e.
export function hello() {
console.log('hi');
}
3.Import your file inside your component as below.
import * as ext from '../assets/some-external.js';
4.Now you can reference it like
ext.hello();

Steps:-
1. create a external js file.
2. In component.ts use the below code.
ngOnInit() {
this.loadJsFile(JsFilePath);
}
public loadJsFile(url) {
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
}
3. If u use jquery then define selector in html to render. Or store data in variable.
Make sure you have to add jquery cdn in index.html and you have to install Jquery and its types package from npm.

Related

Importing javascript file for use within vue component

I am working on a project that requires using a js plugin. Now that we're using vue and we have a component to handle the plugin based logic, I need to import the js plugin file within the vue component in order to initialize the plugin.
Previously, this was handled within the markup as follows:
<script src="//api.myplugincom/widget/mykey.js
"></script>
This is what I tried, but I am getting a compile time error:
MyComponent.vue
import Vue from 'vue';
import * from '//api.myplugincom/widget/mykey.js';
export default {
data: {
My question is, what is the proper way to import this javascript file so I can use it within my vue component?
...
Include an external JavaScript file
Try including your (external) JavaScript into the mounted hook of your Vue component.
<script>
export default {
mounted() {
const plugin = document.createElement("script");
plugin.setAttribute(
"src",
"//api.myplugincom/widget/mykey.js"
);
plugin.async = true;
document.head.appendChild(plugin);
}
};
</script>
Reference: How to include a tag on a Vue component
Import a local JavaScript file
In the case that you would like to import a local JavaScript in your Vue component, you can import it this way:
MyComponent.vue
<script>
import * as mykey from '../assets/js/mykey.js'
export default {
data() {
return {
message: `Hello ${mykey.MY_CONST}!` // Hello Vue.js!
}
}
}
</script>
Suppose your project structure looks like:
src
- assets
- js
- mykey.js
- components
MyComponent.vue
And you can export variables or functions in mykey.js:
export let myVariable = {};
export const MY_CONST = 'Vue.js';
export function myFoo(a, b) {
return a + b;
}
Note: checked with Vue.js version 2.6.10
try to download this script
import * from '{path}/mykey.js'.
or import script
<script src="//api.myplugincom/widget/mykey.js"></script>
in <head>, use global variable in your component.
For scripts you bring in the browser way (i.e., with tags), they generally make some variable available globally.
For these, you don't have to import anything. They'll just be available.
If you are using something like Webstorm (or any of the related JetBrains IDEs), you can add /* global globalValueHere */ to let it know that "hey, this isn't defined in my file, but it exists." It isn't required, but it'll make the "undefined" squiggly lines go away.
For example:
/* global Vue */
is what I use when I am pulling Vue down from a CDN (instead of using it directly).
Beyond that, you just use it as you normally would.
I wanted to embed a script on my component and tried everything mentioned above, but the script contains document.write. Then I found a short article on Medium about using postscribe which was an easy fix and resolved the matter.
npm i postscribe --save
Then I was able to go from there. I disabled the useless escape from eslint and used #gist as the template's single root element id:
import postscribe from 'postscribe';
export default {
name: "MyTemplate",
mounted: function() {
postscribe(
"#gist",
/* eslint-disable-next-line */
`<script src='...'><\/script>`
);
},
The article is here for reference:
https://medium.com/#gaute.meek/how-to-add-a-script-tag-in-a-vue-component-34f57b2fe9bd
For anyone including an external JS file and having trouble accessing the jQuery prototype method(s) inside of the loaded script.
Sample projects I saw in vanilla JS, React and Angular were simply using:
$("#someId").somePlugin(options)
or
window.$("#someId").somePlugin(options)
But when I try either of those in my VueJS component I receive:
Error: _webpack_provided_window_dot$(...).somePluginis not a function
I examined the window object after the resources had loaded I was able to find the jQuery prototype method in the window.self read-only property that returns the window itself:
window.self.$("#someId").somePlugin(options)
Many examples show how to load the external JS file in VueJS but not actually using the jQuery prototype methods within the component.

How to call an external javascript library function within a Typescript class using Angular 2/4?

I have a Typescript class class.component.ts in which I want to call methods which are defined within my Javascript class. This Javascript class is headed within: /assets/js/*initlibrary.js*. This javascript library is automatically called when the project is initialized.
My question is: how can I reach out to this javascript library and call the function in it? Is it required to import it in a way like import { Component, OnInit } from '#angular/core';? If so, how should I do this?
Thank you in advance!
If you want to use an external library inside your angular project, there are many requirements.
1. Declare your javascript library inside your angular-cli.json :
"scripts": [
"../assets/js/yourlibrary.js"
]
With this instruction, you can use your library function inside your typescript code, but it will not be able to compile (transpile).
2. Create a definition of your library
A typescript definition has an extension file ends with .d.ts. You can create it inside your project and reference it from your tsconfig.json.
Here is an example of the EXIF library definition that I've created :
/// EXIF.d.ts
declare module EXIF {
interface EXIFStatic {
getData(img, callback): boolean;
getTag(img, tag): any;
getAllTags(img): any;
pretty(img): any;
readFromBinaryFile(file): any;
}
}
declare var EXIF: EXIF.EXIFStatic;
declare module "EXIF" {
export = EXIF;
}
In my code, I use like this :
EXIF.getData(img,callback);
You can find more example here : https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types
3. Reference the definition of your library
Here is an example of my tsconfig.json file :
"typeRoots": [
"./typings" // I have create a typings folder inside my src project folder
],
"types": [
"EXIF" // Reference of your EXIF.d.ts inside your typings folder
]
The definition allows you to get autocomplete function name when you code (if you use Visual studio code), and allows angular to build your project.

How to access external javascript file from angular 2 component

I am very new to angular and front end web development, so maybe i am missing something
basic but i did not succeed to search a solution for that issue.
according to that answer: Call pure javascript function from Angular 2 component
and following that example
I am trying to import external .js file to my angular component:
import '../../../src/Plugin/codemirror/mode/custom/custom.js'
#Component({
selector: 'txt-zone',
templateUrl: 'app/txtzone/Txtzone.component.html',
styleUrls: ['app/txtzone/TxtZone.css'],
})
the path is the correct relative path, i know that because if it loads diractly from the url text box via the browser [http://localhost:50371/src/Plugin/codemirror/mode/custom/custom.js]
i can see the file content...
this is the exception that the chrome debugger is throwing:
zone.js:2263 GET
http://localhost:50371/src/Plugin/codemirror/lib/codemirror 404 (Not
Found)
as you can see the path was changed (don`t understand why?)
1. how can i solve this issue?
2. why the path of the .js file is not the referenced path?
3. maybe there is a better way to load external .js file into my component?
it looks quite trivial question but after hours of searching i could not find any answer.
A simple way to include custom javascript functions in your Angular 4 project is to include the item in your assets folder, and then use require to import it into your component typescript.
src/assets/example.js
export function test() {
console.log('test');
}
src/app/app.component.ts
(before #Component(...))
declare var require: any;
const example = require('../assets/example');
(inside export class AppComponent implements OnInit { ...)
ngOnInit() {
example.test();
}

How to include external JavaScript libraries in Angular 2?

I am trying to include an external JS library in my Angular 2 app and trying to make all the methods in that JS file as a service in Angular 2 app.
For eg: lets say my JS file contains.
var hello = {
helloworld : function(){
console.log('helloworld');
},
gmorning : function(){
console.log('good morning');
}
}
So I am trying to use this JS file and reuse all the methods in this object and add it to a service, so that my service has public methods, which in turn calls this JS methods. I am trying to reuse the code, without reimplementing all the methods in my typescript based Angular 2 app. I am dependent on an external library, which I cant modify.
Please help, thank you in advance.
With ES6, you could export your variable:
export var hello = {
(...)
};
and import it like this into another module:
import {hello} from './hello-module';
assuming that the first module is located into the hello-module.js file and in the same folder than the second one. It's not necessary to have them in the same folder (you can do something like that: import {hello} from '../folder/hello-module';). What is important is that the folder is correctly handled by SystemJS (for example with the configuration in the packages block).
When using external libs which are loaded into the browser externally (e.g. by the index.html) you just need to say your services/component that it is defined via "declare" and then just use it. For example I recently used socket.io in my angular2 component:
import { Component, Input, Observable, AfterContentInit } from angular2/angular2';
import { Http } from 'angular2/http';
//needed to use socket.io! io is globally known by the browser!
declare var io:any;
#Component({
selector: 'my-weather-cmp',
template: `...`
})
export class WeatherComp implements AfterContentInit{
//the socket.io connection
public weather:any;
//the temperature stream as Observable
public temperature:Observable<number>;
//#Input() isn't set yet
constructor(public http: Http) {
const BASE_URL = 'ws://'+location.hostname+':'+location.port;
this.weather = io(BASE_URL+'/weather');
//log any messages from the message event of socket.io
this.weather.on('message', (data:any) =>{
console.log(data);
});
}
//#Input() is set now!
ngAfterContentInit():void {
//add Observable
this.temperature = Observable.fromEvent(this.weather, this.city);
}
}

Referencing in a simple way using AngularJS and TypeScript

I'm using VS2015 with Gulp and I'm trying to build AngularJS with TypeScript.
In my index.html, I have a script tag to my "app.js" (the output and bundle of the TS build).
However if I want to reference my controller, and any other services - how can I avoid having to put the relevant script tags in each and every HTML file - is there a way I can just reference the app.js file and be done with it? What's the recommended approach?
Cheers,
if you want to refrence only one file in html via script tag and other files just reference in other js files then you can use requirejs. It is a nice tool to load scripts. in production it is a good approach to concat and minify all your scripts to reduce number of requests.
I managed to resolve it using experimental typescript decorators, requirejs and a little of imagination.
So, in resume I wrote two decorators one called AppStartup and other called DependsOn. So at angular bootstrap I can get and register all dependencies.
I ended up with something like it:
TodoListController.ts
import {DependsOn, AppStartup, ngControllerBase} from "../infra/core";
import {taskManagerDirective} from "../directives/TaskManagerDirective";
#AppStartup({
Name: "TodoSample"
}).Controller({
DependsOn: [taskManagerDirective]
})
export class TodoListController extends ngControllerBase {
public ByControllerAs: string;
constructor() {
super(arguments);
let $httpPromise = this.$get<ng.IHttpService>("$http");
$httpPromise.then(function ($http) {
$http.get('http://www.google.com').success(function (body) {
console.info("google.com downloaded, source code: ", body);
});
});
this.ByControllerAs = "This was included by controllerAs 'this'";
}
}
rowListItemDirective.ts
import {DependsOn, ngDirectiveBase} from "../infra/core";
import {rowListItemDirective} from "./RowListItemDirective";
#DependsOn([rowListItemDirective])
export class taskManagerDirective extends ngDirectiveBase{
public template: string = `
Parent Directive
<table>
<tbody>
<tr row-list-item-directive></tr>
</tbody>
</table>
`;
}
You can see what I did below at my github repository:
https://github.com/klaygomes/angular-typescript-jasmine-seed

Categories

Resources