How to use JavaScript files in angular - javascript

I am trying to call the javascript function into the angular here is the plugin I am using "npm I global payments-3ds" of which I copied javascript files from node_modules and tried to call in my component
Below is the example :
import {
Component,
OnInit
} from '#angular/core';
import {
handleInitiateAuthentication
} from './globalpayments-3ds/types/index';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
name = 'Angular';
ngOnInit(): void {
const status: any = "CHALLENGE_REQUIRED"
const resp = {
challenge: {
encodedChallengeRequest: "abcd",
requestUrl: "url,
},
challengeMandated: "MANDATED",
dsTransactionId: "44444",
id: "444444",
status: status,
};
const windowSize: any = "WINDOWED_600X400";
const displayMode: any = "lightbox";
const challengeWindow = {
windowSize: windowSize,
displayMode: displayMode,
};
handleInitiateAuthentication(resp, challengeWindow)
}
}
I am trying to call the handleInitiateAuthentication() which is giving me the below error
Here is the file structure
from index.d.ts i am calling the handleInitiateAuthentication() function
Here is Stackblitz code for the same
https://stackblitz.com/edit/angular-vodezz?file=src%2Fapp%2Fapp.component.ts
Please help I never used the js function in angular I tried to add in assets not worked
I have tried to create an angular library and add the js files in it and update the package, by converting the file to .tgz but nothing working it showing always the same error,
Why am I doing is I have to update one of the files from node_modules, basically I wanna change files from node modules which is why i copied those files locally
this is also giving error

You have to import directly js file.
// #ts-ignore
import { handleInitiateAuthentication } from './globalpayments-3ds/globalpayments-3ds.esm.js';
For error about module, it's because you have to define type of your module in TypeScript. You can directly use // #ts-ignore.
See this stackblitz : https://stackblitz.com/edit/angular-xz4kmp?file=src%2Fapp%2Fapp.component.ts

You don't need to import a library like that. First of all install the library to your project:
npm i globalpayments-3ds --save
then in your ts file:
import { handleInitiateAuthentication } from 'globalpayments-3ds';
see this stackblitz

The recommended way to make your own modified versions from open source libraries is to fork them and build your own versions.
Also note that you must take into account the license of that NPM package which in the case of https://github.com/globalpayments/globalpayments-js is GPL-v2, so if you will use it for commercial purposes you must follow the agreement. Check this branch: GNU General Public License (v2): can a company use the licensed software for free?.
Taking a look to your Stackblitz code, you may notice that there are several JS versions of the same module in src/app/global-payments-3ds/ folder:
globalpayments-3ds.js (CommonJS, used in Node environments).
globalpayments-3ds.min.js (CommonJS minified).
globalpayments-3ds.js.map (CommonJS minified map file to reference during debugging).
globalpayments-3ds.esm.js (ESM, ECMA Standard Module).
...
To use an external JS Module in an Angular App, as it is JavaScript and not TypeScript, you must tell TypeScript Compiler that you want to allow JS modules by enabling allowJS: true in tsconfig.ts file at the root of the project.
After that you should be be able to import the ESM version (globalpayments-3ds.esm.js) in your Angular App, or if you want to use the CommonJS version, you can also enable esModuleInterop: true in tsconfig.ts to allow importing CommonJS/AMD/UMD JS modules in your project, like globalpayments-3ds.js.

Related

How to use Chrome Extension Api with Angular?

I am working on a chrome extension, I have a "background.js" which it filters the url and fetchs data from my api. When the conditions is meet I am sending a message from "background.js". And I want to catch it from Angular component.
background.js
...
chrome.pageAction.show(tab.id, () => {
chrome.runtime.sendMessage({data: dataFromAPI})
});
...
I ran npm install --save #types/chrome.
app.component.ts
import {Component} from '#angular/core';
import {chrome} from '#types/chrome';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
chrome.runtime.onMessage.addListener( data => console.log(data));
}
}
But WebStorm says, ".../node_modules/#types/chrome/index.d.ts' is not a module. "
How can I use Chrome Api from Angular Component?
/// <reference types="chrome"/>
import {chrome} from '#types/chrome';
// Remove chrome import
IMPORTANT: Must add three slashes before reference.
If still it doesn't work then add "Chrome" in tsconfig.json types.
compilerOptions: ["types": [ "Chrome" ] ]
Add the line
///<reference types="chrome"/>
to the very top of your TS file (preferably line 1). (DO NOT OMIT THE 3 SLASHES IN THE BEGINNING)
Also run the command
npm install --save #types/chrome
Things will start working after that.
In my case, I installed npm install --save #types/chrome
so file stop showing an error Cannot find name 'chrome' when build
then I'm trying to build the library by using the command ng build but it was broken because it didn't find a chrome so what I did?
I added this line ///<reference types="chrome"/> on top of file public-api.ts
Note: Must add three slashes(///) before reference.

How do I manually include "#material/drawer" into my component?

I am trying to manually include the #material/drawer npm package into my Ember app. I tried following this guide but I'm running into some weird errors in my Chrome dev console:
Uncaught SyntaxError: Unexpected token *
Uncaught ReferenceError: define is not defined
The first is from the imported node_modules/#material/drawer/index.js file and the second is from my generated shim.
My component code:
import Component from '#ember/component';
import { MDCTemporaryDrawer, MDCTemporaryDrawerFoundation, util } from '#material/drawer';
export default Component.extend({
init() {
this._super(...arguments);
const drawer = new MDCTemporaryDrawer(document.querySelector('.mdc-drawer--temporary'));
document.querySelector('.menu').addEventListener('click', () => drawer.open = true);
}
});
In my ember-cli-build.js:
app.import('node_modules/#material/drawer/index.js');
app.import('vendor/shims/#material/drawer.js');
My generated shim:
(function() {
function vendorModule() {
'use strict';
return {
'default': self['#material/drawer'],
__esModule: true,
};
}
define('#material/drawer', [], vendorModule);
})();
What exactly am I doing wrong? It almost seems as though raw ES6 code got imported rather than compiled into my JS build output.
I also read this SO post but there are too many answers and I'm not sure which to do. It seems this specific answer is what I'm trying to do but not verbatim enough.
Creating a shim only ensures that ember-cli gets an AMD module, which you then can import in your app files.
If the npm package needs a build or transpiling step beforhand, this won't work.
You need a way to get the package build within the ember-cli build pipeline.
Luckily there are addons which can take care of this for you: ember-auto-import and ember-cli-cjs-transform.
You may have also heard of ember-browserify, which does the same thing, but it's deprectaed in favor of ember-auto-import.
I'd suggest you try ember-auto-import:
ember install ember-auto-import
You then should be able to import as you tried:
import { MDCTemporaryDrawer, MDCTemporaryDrawerFoundation, util } from '#material/drawer';
No shim or app.import needed, as ember-auto-import will take care of this for you.

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

How to import Parse JS sdk into ionic 2 beta

am trying to import JS sdk into ionic 2 app, but i keep getting parse is undefined
In ionic 1.x ,parse js sdk is loaded via
<script ..parse.js </script>
and exposed as a global var, how do import in ionic 2 ,am using the npm module ,and tried
import * as parse from 'parse'
Do npm install parse --save in your project directory
Then import parse using
import { Parse } from 'parse';
It is better to create an parse provider.
You can use this starter template as a guide. It is a simple GameScores application in ionic to get you started.
https://github.com/Reinsys/Ionic-Parse
It shows how to create and read data from parse server. I also includes paging with ion-infinite-scroll scrolling.
After searching for a solution I came up with my own.
After installing the package and the typings, I opened the index.js of the node-module ionic-gulp-scripts-copy and added 'node_modules/parse/dist/parse.min.js' to the defaultSrc array.
Then, in my index.html, I included the script above the cordova.js.
Now I just need to declare var Parse: any; in every Component I want to use the SDK in.
For example, in my app.ts:
import {Component} from '#angular/core';
import {Platform, ionicBootstrap} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {TabsPage} from './pages/tabs/tabs';
import{LoginPage} from './pages/login/login';
declare var Parse: any;
#Component({
template: '<ion-nav [root]="rootPage"></ion-nav>',
})
export class MyApp {
private rootPage: any;
private parse;
constructor(private platform: Platform) {
//this.rootPage = TabsPage;
this.rootPage = LoginPage;
platform.ready().then(() => {
console.log("Platform ready!");
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Parse.initialize('myStartUp', 'someKey');
Parse.serverURL = 'http://localhost:1337/parse';
});
}
}
ionicBootstrap(MyApp);
I do not think this is the way it should be used, but in the end I can use the SDK pretty easy and without much lines of implementation code.

Use third party library (parse.com) in Angular 2

I am learning Angular 2 and I followed the tutorials of Egghead already, but I am pretty new to everything concerning Angular.
Now I want to do something more advanced and start using Parse.com with Angular 2.
Normally I would include the parse.com library in the index.html page via <script src="//www.parsecdn.com/js/parse-1.6.2.min.js"></script>, but I want to write a ParseService via Angular 2 that I can use to manage the backend.
I can't seem to find how to include and use Parse in the service I want to write.
This is the very basic code I want to use to test the import.
import {Injectable} from 'angular2/core';
import {Parse} from '.../...'; // <-- This is what I want to do
#Injectable()
export class ParseService {
constructor() {
console.log('Creating ParseService');
Parse.initialize('', '');
}
}
I need some kind of Import at the top of the page including Parse, but from where should I get the necessary library? I already tried via npm but without success. Anyone already tried this?
uksz was right. You has to first install the component by the command
npm install --save parse
After that you can import it as any other component by typing
import {Parse} from 'parse';
For more info look at this link https://forum.ionicframework.com/t/how-to-require-xyz-in-ionic2-angular2/42042
Hope it helps;)
UPDATED
With new version of angular this approach stopped to work. Here is my new step by step: how to use Parse library in Angular2
Install Parse component to the project
npm install parse --save
Install Parse types
npm install #types/parse --save
import Parse module
const Parse: any = require('parse');
use Parse module
Parse.initialize("key");
...
Enjoy it with intellisense;)
You can do that by using OpaqueToken in Angular2
1. Create a Token that is used to find an instance as below in a separate ts file.
import { OpaqueToken } from '#angular/core'
export let name_of_The_Token = new OpaqueToken('name_Of_The_Window_Object');
2. In your App.module, you need to import and declare a variable that is the name of your window object which makes the Token as a angular2 service so that you can use properties, methods in that javascript file across your components.
import { name_of_The_Token } from '/* file_Path */';
declare let name_Of_The_Window_Object : any; //below your import statements
Step 3: Inject it to providers array of your module.
{ provide : name_of_The_Token , useValue : name_Of_The_Window_Object }
Guidance to use this token in components
Import the token just like any other service and #Inject from angular-core
import { name_of_The_Token } from '/* file_Path */';
import { Inject } from '#angular/core';
In constructor of the component
constructor(#Inject( name_of_The_Token ) private _serviceObject : any )
Any where in your component you can use the variables and methods of your javascript file as
this._serviceObject.method1()
this._serviceObject.variable1
.....
Note: One drawback is that you will not get intellisense.
Overcoming it:
If you are looking for intellisense you need to wrap the methods and variables inside an interface and use it in the type**(instead of any)** of your token as
export interface myCustom {
method1(args): return_Type;
method2(args): void;
.....
}
What you need to do, is you need to download Parse library with:
npm install parse
Then, you need to reference it in your import in the right way - you need to specify in which folder the parse.js file is placed at.

Categories

Resources