How to import Parse JS sdk into ionic 2 beta - javascript

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.

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.

Cannot import Amplitude SDK in a Ionic 3 app

I'm trying to use Amplitude SDK to get statistics from my Ionic 3 app. However, since the app is written in TypeScript with a certain file architecture, it is not as simple as in the official documentation.
However, I found the #types/amplitude-js package and I thought it would resolve all my problems. But unfortunately, when I compile my app on my device using ionic cordova run android --device, the app doesn't load and I get the following error message:
Uncaught Error: Encountered undefined provider!
Usually this means you have a circular dependencies (might be caused by using 'barrel' index.ts files.
Note: this error also appears when I run ionic serve.
Here is what I did, step by step:
I installed the #types/amplitude-js by running npm install --save #types/amplitude-js.
I installed the original Amplitude SDK by running npm install amplitude-js. I noticed it was necessary to do that, otherwise my app wouldn't compile with only the #type package (which makes sense).
I added the following lines to my app.module.ts
import { AmplitudeClient } from 'amplitude-js';
[...]
#NgModule({
[...]
providers: [
AmplitudeClient,
[...]
]
});
I also created an AmplitudeProvider, which will manage all my Amplitude events throughout my app:
import { Injectable } from '#angular/core';
import { HttpServiceProvider } from "../http-service/http-service";
import { AmplitudeClient } from 'amplitude-js';
/**
* AmplitudeProvider
* #description Handles Amplitude statistics
*/
#Injectable()
export class AmplitudeProvider {
constructor(
public http: HttpServiceProvider,
public amplitude: AmplitudeClient
) {
this.amplitude.init("MY_AMPLITUDE_KEY");
}
/**
* logEvent
* #description Logs an event in Amplitude
* #param eventTitle Title of the event
*/
public logEvent(title) {
// Do things not relevant here
}
}
I'm certain that I'm doing something wrong with my dependency injection and/or my imports, but I don't understand what. And I don't see any circular dependency, since the amplitude-js package is not made by me and does not import any of my providers.
Thanks in advance to anyone who will point me in the right direction!
AmplitudeClient is not a Ionic Provider, therefore, you can't import it and put in your Class constructor.
To use amplitude in your Provider you want to import amplitude. Your code should be similar to this.
import amplitude, { AmplitudeClient } from 'amplitude-js';
#Injectable()
export class AmplitudeProvider {
private client: AmplitudeClient;
constructor(
public http: HttpServiceProvider,
public database: DatabaseProvider
) {
this.client = amplitude.getInstance();
this.client.init("MY_AMPLITUDE_KEY");
}
}

Cannot instantiate pubnub sdk in angular 2 + typescript application

I am trying to use the pubnub javascript 4.0 sdk within my Angular 2 application that is using Typescript. I have successfully installed the library through npm and linked the module using SystemJS, and I can import it into my service that I'm using for chat. The problem comes when I try to access it within the service itself, I get a Error: CompileMetadataResolver. There are no type definitions for this library, so I found an open source .d.ts file someone posted online. Am I missing a type file (hence the metadata resolve)?
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import {PUBNUB} from 'pubnub';
export class ChatService {
private pnService: PUBNUB.PUBNUB;
constructor(private pubNub: PUBNUB){
//trying to access or create object here results in error
this.pnService = new
}
initialize(subkey:string, pubKey:string) {
//this.pubNub.init({subscribe_key : subKey, publish_key : pubKey, ssl: true, origin: 'pubsub.pubnub.com'});
}
}

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

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