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

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.

Related

How to use JavaScript files in angular

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.

How can I use a *.d.ts outside of the node_modules folder for my Angular library?

I have an angular 8 library I'm creating and it's going to utilize the insane.js npm package. Because insane is JavaScript, I need to make it so that my typescript service recognizes the insane function. I used dts-gen to create an insane.d.ts file as there is no #types/insane package. However, I can't use the import in my service unless I place the insane.d.ts file within the /node_modules/insane/ folder. That said, I'm at a loss on how to put this file in with my code and recognize the insane function. Every time I move the file out of that directory, I receive an error on my import line saying:
Could not find a declaration file for module 'insane'. 'c:/TFS/repo/amrock-simple-mde/projects/simple-mde/node_modules/insane/insane.js' implicitly has an 'any' type.
I've provided a stackblitz link here to help describe what I'm experiencing. I hope it helps. Check out the SanitizerService under the shared folder to get an idea of what I was trying to do. I'm trying to do something to the effect of:
import { Injectable } from '#angular/core';
import * as insane from 'insane'; // line where error is
#Injectable({
providedIn: 'root'
})
export class SanitizerService {
constructor() { }
sanitize(content: string): string {
return insane(content, {
allowedAttributes: {
a: ['name', 'target']
}
});
}
}
I'd expect the import to recognize the insane.d.ts, but it doesn't. Can anyone help me figure out what I'm missing?
You'll want to use a declare module statement for this:
declare module 'insane' {
// ...
}
Essentially wrap your whole .d.ts file in the declare module block and remove all existing declare keywords since those are not valid inside a declare module block.
Secondly, make sure that the .d.ts file is included by TypeScript. Usually the easiest way to do this is to specify it in the include option of your tsconfig.json.
Updated Stackblitz

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

Angular2 dependency not injecting correct path

I am getting the following errors in my browser console, from trying to use localStorage with Angular2. It seems that the path it is generating isn't referring to the node_modules, but rather assuming that there is a localstorage.js in my site root (which there isn't). I am just referring to it normally (see my user.service below), so how do I get around this? All my other dependencies are working fine.
Error loading http://localhost:3000/localStorage.js as "localStorage" from http://localhost:3000/client/dev/user/services/user.service.js
import { Injectable } from 'angular2/core';
import { Headers } from 'angular2/http';
import { loalStorage } from 'localStorage';
#Injectable()
export class UserService {
private loggedIn = false;
constructor(private http: Http) {
this.loggedIn = !!localStorage.getItem('auth_token');
}
}
NB: I am fairly sure there isn't an actual problem with the localStorage installation, as if I run npm list localStorage, then it tells me I have localStorage#1.0.3 instaled.
If you want to use localStorage from an import, you need to configure it within SystemJS as described below:
System.config({
map: {
localStorage: 'node_modules/localStorage/lib/localStorage.js'
},
(...)
});
This way, you will be able to use the following import:
import loalStorage from 'localStorage';
See this question for more details since it's similar to the way to configure Lodash:
Lodash in angular2, declare var_:any not working

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.

Categories

Resources